/* listgetbuy — Buyer scroll story (scroll-position driven, hız bağımsız) */
const { useState, useEffect, useRef } = React;

const clamp = (v, a = 0, b = 1) => Math.max(a, Math.min(b, v));
const lerp = (a, b, t) => a + (b - a) * t;
const easeIO = (t) => (t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2);
const TL = (n) => '€' + Math.round(n).toLocaleString('de-DE');

const BUDGET = 950;
const LOW = 790;
const TH = [0.04, 0.30, 0.58, 0.86]; // offer i appears at this t within offer band
const B = { introEnd: 0.12, offEnd: 0.50, dealEnd: 0.66, payEnd: 0.84 };

const STEPS_LANG = {
  tr: [
    { k: '01', t: 'İlanını aç, bütçeni koy', s: 'Aramak yok. Ne istediğini yaz, satıcılar sana gelsin.' },
    { k: '02', t: 'Teklifler düşerek gelir', s: 'Satıcılar teklifleriyle yarışır. Sen izlersin, fiyat düşer.' },
    { k: '03', t: 'Süre dolar, en ucuz kazanır', s: 'Pazarlık yok, kovalamaca yok. En düşük teklif anlaşmayı alır.' },
    { k: '04', t: 'Tek dokunuşla güvenli öde', s: 'Anlaş, öde, bitir. Para satıcıya teslimde geçer.' },
    { k: '05', t: 'Bütçenin altında aldın', s: 'İşte eksiltme: zahmetsiz, ucuza. Aradaki fark cebinde kalır.' },
  ],
  en: [
    { k: '01', t: 'Open your listing, set budget', s: 'No searching. Just write what you need, let sellers come to you.' },
    { k: '02', t: 'Offers come dropping down', s: 'Each new seller underbids the previous one. Watch the price drop.' },
    { k: '03', t: 'Time expires, cheapest wins', s: 'No bargaining, no chasing. The lowest offer secures the deal.' },
    { k: '04', t: 'One-tap secure payment', s: 'Agree, pay, finish. Funds are transferred to the seller upon delivery.' },
    { k: '05', t: 'You bought below budget', s: 'That\'s the reverse auction: effortless, cheap. The difference stays in your pocket.' },
  ],
  de: [
    { k: '01', t: 'Inserat erstellen, Budget festlegen', s: 'Kein Suchen. Schreibe, was du brauchst, lass Verkäufer zu dir kommen.' },
    { k: '02', t: 'Angebote sinken automatisch', s: 'Jeder neue Verkäufer unterbietet den vorherigen. Sieh zu, wie der Preis fällt.' },
    { k: '03', t: 'Zeit läuft ab, der Günstigste gewinnt', s: 'Kein Feilschen, kein Hinterherjagen. Das niedrigste Angebot erhält den Zuschlag.' },
    { k: '04', t: 'Sichere Zahlung per Klick', s: 'Einigen, bezahlen, fertig. Das Geld geht erst bei Lieferung an den Verkäufer.' },
    { k: '05', t: 'Unter dem Budget gekauft', s: 'Das ist die Rückwärtsauktion: mühelos, günstig. Die Differenz bleibt in deiner Tasche.' },
  ],
};

const L_LABELS = {
  tr: {
    budget: 'Bütçe',
    timeUp: 'Süre doldu',
    paidUp: 'ÖDENEN',
    lowestOffer: 'EN DÜŞÜK TEKLİF',
    initialBudget: 'BAŞLANGIÇ BÜTÇESİ',
    dropped: 'düştü',
    willBeat: 'Satıcılar bunu kırmaya çalışacak',
    livePending: 'İlanın yayında. Teklifler düşmeye başlamak üzere…',
    shop: 'MAĞAZA',
    lowest: 'EN DÜŞÜK',
    outbid: 'GEÇİLDİ',
    dealSecured: 'Anlaşma sağlandı',
    lowestGiver: 'En düşük teklifi verdi',
    securePay: 'Güvenli ödeme',
    payDesc: 'Para, ürün eline geçince satıcıya aktarılır.',
    amount: 'Tutar',
    makePay: 'Ödemeyi yap',
    confirming: 'Onaylanıyor…',
    paid: 'ödendi',
    below: 'altında',
    city: 'İstanbul',
    notes: {
      elif: 'Faturalı, temiz cihaz',
      burak: 'Deep Purple, kutulu',
      mert: 'Pil %91, çiziksiz',
      tekno: 'Kutulu · faturalı · 8 ay garanti'
    }
  },
  en: {
    budget: 'Budget',
    timeUp: 'Time expired',
    paidUp: 'PAID',
    lowestOffer: 'LOWEST OFFER',
    initialBudget: 'INITIAL BUDGET',
    dropped: 'dropped',
    willBeat: 'Sellers will try to beat this',
    livePending: 'Your listing is live. Offers are about to start dropping…',
    shop: 'STORE',
    lowest: 'LOWEST',
    outbid: 'OUTBID',
    dealSecured: 'Deal secured',
    lowestGiver: 'Gave the lowest offer',
    securePay: 'Secure payment',
    payDesc: 'Funds are released to the seller upon delivery.',
    amount: 'Amount',
    makePay: 'Make payment',
    confirming: 'Confirming…',
    paid: 'paid',
    below: 'below',
    city: 'Istanbul',
    notes: {
      elif: 'Invoice included, clean device',
      burak: 'Deep Purple, boxed',
      mert: 'Battery 91%, scratchless',
      tekno: 'Boxed · Invoice · 8mo warranty'
    }
  },
  de: {
    budget: 'Budget',
    timeUp: 'Abgelaufen',
    paidUp: 'BEZAHLT',
    lowestOffer: 'NIEDRIGSTES ANGEBOT',
    initialBudget: 'STARTBUDGET',
    dropped: 'gesunken',
    willBeat: 'Verkäufer werden dies unterbieten',
    livePending: 'Ihr Inserat ist live. Angebote starten in Kürze…',
    shop: 'SHOP',
    lowest: 'BESTES',
    outbid: 'ÜBERBOTEN',
    dealSecured: 'Deal gesichert',
    lowestGiver: 'Hat das niedrigste Angebot abgegeben',
    securePay: 'Sichere Zahlung',
    payDesc: 'Geld wird erst bei Lieferung freigegeben.',
    amount: 'Betrag',
    makePay: 'Zahlung tätigen',
    confirming: 'Bestätigen…',
    paid: 'bezahlt',
    below: 'unter',
    city: 'Istanbul',
    notes: {
      elif: 'Mit Rechnung, sauberes Gerät',
      burak: 'Deep Purple, mit OVP',
      mert: 'Batterie 91%, kratzfrei',
      tekno: 'Mit OVP · Rechnung · 8 Monate Garantie'
    }
  }
};

function Avatar({ o, size = 38 }) {
  const url = o.avatar || o.avatar_url;
  return (
    <div style={{
      width: size, height: size, borderRadius: o.shop ? size * 0.28 : 999, flexShrink: 0,
      background: url ? '#ddd' : `oklch(0.93 0.05 ${o.hue})`, color: `oklch(0.45 0.12 ${o.hue})`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.36, fontWeight: 800, letterSpacing: '-0.02em',
      overflow: 'hidden',
    }}>
      {url ? <img src={url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : o.initials}
    </div>
  );
}

function OfferRow({ o, leader, beaten, reveal = 1, labels }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 11, padding: '11px 13px', borderRadius: 16,
      background: leader ? 'var(--green-soft)' : 'var(--surface)',
      boxShadow: leader ? '0 0 0 1.5px var(--green)' : 'inset 0 0 0 1px var(--line)',
      opacity: (beaten ? 0.5 : 1) * reveal,
      transform: `translateY(${(1 - reveal) * 12}px)`,
      transition: 'background .3s, box-shadow .3s',
    }}>
      <Avatar o={o} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontSize: 14, fontWeight: 800, color: 'var(--ink)' }}>{o.name}</span>
          {o.shop && <span className="mono" style={{ fontSize: 9, fontWeight: 700, color: 'var(--green-ink)', background: '#fff', padding: '2px 5px', borderRadius: 6, boxShadow: 'inset 0 0 0 1px var(--green)' }}>{labels.shop}</span>}
        </div>
        <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--muted)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{o.note}</div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className="mono" style={{ fontSize: 15, fontWeight: 700, color: leader ? 'var(--green-ink)' : 'var(--ink)', textDecoration: beaten ? 'line-through' : 'none' }}>{TL(o.price)}</div>
        {leader ? (
          <div className="mono" style={{ fontSize: 8.5, fontWeight: 700, color: 'var(--green-ink)', letterSpacing: '0.08em' }}>{labels.lowest}</div>
        ) : beaten ? (
          <div className="mono" style={{ fontSize: 8.5, fontWeight: 700, color: 'var(--muted)', letterSpacing: '0.06em' }}>{labels.outbid}</div>
        ) : null}
      </div>
    </div>
  );
}

function Stage({ p, lang = 'tr' }) {
  const labels = L_LABELS[lang] || L_LABELS.tr;
  const OFFERS = [
    { initials: 'ED', hue: 285, name: 'Elif D.',      note: labels.notes.elif,   price: 890, avatar: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?auto=format&fit=crop&w=120&h=120&q=80' },
    { initials: 'BT', hue: 25,  name: 'Burak T.',     note: labels.notes.burak,  price: 850, avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?auto=format&fit=crop&w=120&h=120&q=80' },
    { initials: 'MK', hue: 158, name: 'Mert K.',      note: labels.notes.mert,   price: 820, avatar: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?auto=format&fit=crop&w=120&h=120&q=80' },
    { initials: 'TC', hue: 200, name: 'TeknoCenter',  note: labels.notes.tekno,  price: 790, shop: true, avatar: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?auto=format&fit=crop&w=120&h=120&q=80' },
  ];

  const started = p > 0.015;
  const tBand = clamp((p - B.introEnd) / (B.offEnd - B.introEnd));
  const dealLocked = p >= B.offEnd;
  const paying = p >= B.dealEnd;
  const paid = p >= B.payEnd;

  const bigPrice = p < B.introEnd ? BUDGET : lerp(BUDGET, LOW, easeIO(tBand));
  const showLow = p >= B.introEnd;

  const remain = clamp(1 - tBand);
  const totalMin = Math.round(remain * 154); // ~2h34m
  const hh = String(Math.floor(totalMin / 60)).padStart(2, '0');
  const mm = String(totalMin % 60).padStart(2, '0');

  const revealed = OFFERS.map((o, i) => ({ o, i, rev: p < B.introEnd ? 0 : clamp((tBand - TH[i]) / 0.07) }))
    .filter((x) => x.rev > 0.02);
  const shown = revealed.length;
  const ordered = [...revealed].sort((a, b) => a.o.price - b.o.price); // cheapest first
  const ovOp = clamp((p - (B.offEnd - 0.02)) / 0.04);

  const payProg = clamp((p - B.dealEnd) / (B.payEnd - B.dealEnd));

  return (
    <div style={{
      width: 'min(380px, 90vw)', background: 'var(--surface)', borderRadius: 28,
      boxShadow: '0 30px 60px -20px rgba(20,40,30,0.28), 0 0 0 1px var(--line)',
      overflow: 'hidden', position: 'relative',
    }}>
      {/* listing header */}
      <div style={{ padding: '16px 16px 14px', borderBottom: '1px solid var(--line)', background: 'var(--surface)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 42, height: 42, borderRadius: 12, overflow: 'hidden', border: '1px solid var(--line)', flexShrink: 0 }}>
            <img src="https://images.unsplash.com/photo-1678652197831-2d180705cd2c?auto=format&fit=crop&w=120&h=120&q=80" alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14.5, fontWeight: 800, color: 'var(--ink)', letterSpacing: '-0.02em' }}>iPhone 14 Pro · 256GB</div>
            <div className="mono" style={{ fontSize: 11, fontWeight: 600, color: 'var(--muted)' }}>{labels.budget} {TL(BUDGET)} · {labels.city}</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5, background: dealLocked ? 'var(--surface-2)' : 'var(--orange-soft)', padding: '6px 9px', borderRadius: 999 }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: dealLocked ? 'var(--muted)' : 'var(--orange)', animation: dealLocked ? 'none' : 'pulseDot 1.6s infinite' }} />
            <span className="mono" style={{ fontSize: 11, fontWeight: 700, color: dealLocked ? 'var(--muted)' : 'var(--orange)' }}>{dealLocked ? labels.timeUp : `${hh}:${mm}`}</span>
          </div>
        </div>
      </div>

      {/* big descending price */}
      <div style={{ padding: '18px 18px 6px', textAlign: 'center' }}>
        <div className="mono" style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.12em', color: showLow ? 'var(--green-ink)' : 'var(--muted)' }}>
          {paid ? labels.paidUp : showLow ? labels.lowestOffer : labels.initialBudget}
        </div>
        <div className="mono" style={{ fontSize: 46, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1.05, color: showLow ? 'var(--green-ink)' : 'var(--ink-2)', transition: 'color .4s' }}>
          {TL(Math.round((paid ? LOW : bigPrice) / 50) * 50)}
        </div>
        {showLow && !paid && (
          <div className="mono" style={{ fontSize: 11, fontWeight: 700, color: 'var(--green)' }}>
            ↓ {TL(BUDGET - bigPrice)} {labels.dropped}
          </div>
        )}
        {!showLow && (
          <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--muted)' }}>{labels.willBeat}</div>
        )}
      </div>

      {/* offers */}
      <div style={{ padding: '8px 14px 16px', display: 'flex', flexDirection: 'column', gap: 8, minHeight: 220 }}>
        {shown === 0 && (
          <div style={{ textAlign: 'center', padding: '40px 16px', color: 'var(--muted)', fontSize: 13, fontWeight: 600 }}>
            {labels.livePending}
          </div>
        )}
        {ordered.map(({ o, rev }, idx) => (
          <OfferRow key={o.initials} o={o} reveal={rev} leader={idx === 0} beaten={idx !== 0} labels={labels} />
        ))}
      </div>

      {/* deal / payment / paid overlay */}
      {p >= B.offEnd - 0.02 && (
        <div style={{
          position: 'absolute', inset: 0, background: paid ? 'var(--green)' : 'rgba(20,30,25,0.42)',
          backdropFilter: paid ? 'none' : 'blur(3px)', display: 'flex', alignItems: 'flex-end',
          transition: 'background .5s', opacity: ovOp,
        }}>
          {/* deal sheet (anlaşma + ödeme) */}
          {!paid && (
            <div style={{ width: '100%', background: 'var(--surface)', borderRadius: '24px 24px 0 0', padding: '20px 18px 22px', boxShadow: '0 -20px 40px rgba(0,0,0,0.18)' }}>
              {!paying ? (
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
                    <div style={{ width: 26, height: 26, borderRadius: 999, background: 'var(--green)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 15, fontWeight: 800 }}>✓</div>
                    <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--ink)', letterSpacing: '-0.02em' }}>{labels.dealSecured}</div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: 12, background: 'var(--green-soft)', borderRadius: 16, boxShadow: 'inset 0 0 0 1.5px var(--green)' }}>
                    <Avatar o={OFFERS[3]} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 800 }}>TeknoCenter <span className="mono" style={{ fontSize: 9, color: 'var(--green-ink)' }}>4.9★</span></div>
                      <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--muted)' }}>{labels.lowestGiver}</div>
                    </div>
                    <div className="mono" style={{ fontSize: 18, fontWeight: 700, color: 'var(--green-ink)' }}>{TL(LOW)}</div>
                  </div>
                </div>
              ) : (
                <div>
                  <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--ink)', letterSpacing: '-0.02em', marginBottom: 4 }}>{labels.securePay}</div>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--muted)', marginBottom: 14 }}>{labels.payDesc}</div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
                    <span style={{ fontSize: 13, fontWeight: 700, color: 'var(--ink-2)' }}>{labels.amount}</span>
                    <span className="mono" style={{ fontSize: 22, fontWeight: 700, color: 'var(--ink)' }}>{TL(LOW)}</span>
                  </div>
                  <div style={{ height: 46, borderRadius: 14, background: 'var(--green)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 15, fontWeight: 800, position: 'relative', overflow: 'hidden' }}>
                    <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${payProg * 100}%`, background: 'rgba(255,255,255,0.18)' }} />
                    <span style={{ position: 'relative' }}>{payProg > 0.92 ? labels.confirming : labels.makePay}</span>
                  </div>
                </div>
              )}
            </div>
          )}
          {/* paid success */}
          {paid && (
            <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', color: '#fff', padding: 24, textAlign: 'center' }}>
              <div style={{ width: 72, height: 72, borderRadius: 999, background: 'rgba(255,255,255,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 38 }}>✓</div>
              <div style={{ fontSize: 22, fontWeight: 800, margin: '16px 0 2px', letterSpacing: '-0.02em' }}>{TL(LOW)} {labels.paid}</div>
              <div style={{ fontSize: 13.5, fontWeight: 600, opacity: 0.9 }}>iPhone 14 Pro · TeknoCenter</div>
              <div style={{ marginTop: 18, padding: '10px 16px', background: 'rgba(255,255,255,0.16)', borderRadius: 999 }}>
                <span className="mono" style={{ fontSize: 14, fontWeight: 700 }}>{labels.budget} {TL(BUDGET - LOW)} {labels.below} 🎉</span>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function BuyerStory({ lang = 'tr' }) {
  const ref = useRef(null);
  const [p, setP] = useState(0);

  useEffect(() => {
    let raf = 0;
    const update = () => {
      raf = 0;
      const el = ref.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      setP(clamp(-rect.top / total));
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(update); };
    update();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => { window.removeEventListener('scroll', onScroll); window.removeEventListener('resize', onScroll); cancelAnimationFrame(raf); };
  }, []);

  const STEPS = STEPS_LANG[lang] || STEPS_LANG.tr;
  const ai = p < B.introEnd ? 0 : p < B.offEnd ? 1 : p < B.dealEnd ? 2 : p < B.payEnd ? 3 : 4;
  const step = STEPS[ai];

  return (
    <section ref={ref} style={{ position: 'relative', height: '600vh' }}>
      <div style={{ position: 'sticky', top: 0, height: '100vh', display: 'flex', alignItems: 'center', overflow: 'hidden' }}>
        <div style={{ width: 'min(1100px, 100%)', margin: '0 auto', padding: '0 5vw', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 'clamp(24px, 6vw, 80px)', flexWrap: 'wrap' }}>

          {/* narrative column */}
          <div style={{ flex: '1 1 280px', maxWidth: 420, minWidth: 260, ...window.GREEN_THEME }}>
            {/* step rail */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 0, marginBottom: 26 }}>
              {STEPS.map((s, i) => (
                <div key={s.k} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '5px 0', opacity: i === ai ? 1 : 0.32, transition: 'opacity .3s' }}>
                  <span className="mono" style={{ fontSize: 11, fontWeight: 700, color: i === ai ? 'var(--green-ink)' : 'var(--muted)', width: 20 }}>{s.k}</span>
                  <span style={{ height: 2, flex: i === ai ? '0 0 28px' : '0 0 14px', borderRadius: 2, background: i === ai ? 'var(--green)' : 'var(--line2)', transition: 'flex .3s, background .3s' }} />
                  <span style={{ fontSize: 12.5, fontWeight: 700, color: i === ai ? 'var(--ink)' : 'var(--muted)' }}>{s.t}</span>
                </div>
              ))}
            </div>
            <div key={ai}>
              <h2 style={{ fontSize: 'clamp(28px, 4vw, 40px)', fontWeight: 800, letterSpacing: '-0.035em', lineHeight: 1.08, color: 'var(--ink)', margin: '0 0 12px' }}>{step.t}</h2>
              <p style={{ fontSize: 'clamp(15px, 1.6vw, 17px)', fontWeight: 600, lineHeight: 1.5, color: 'var(--ink-2)', margin: 0, textWrap: 'pretty' }}>{step.s}</p>
            </div>
          </div>

          {/* pinned stage */}
          <div style={{ flex: '0 0 auto', display: 'flex', justifyContent: 'center' }}>
            <Stage p={p} lang={lang} />
          </div>

        </div>
      </div>
    </section>
  );
}

window.BuyerStory = BuyerStory;
window.Stage = Stage;
window.__lgb = { TL, BUDGET, LOW, Avatar };

window.GREEN_THEME = {
  '--ink': '#ffffff',
  '--ink-2': 'rgba(255,255,255,0.84)',
  '--muted': 'rgba(255,255,255,0.55)',
  '--green-ink': 'oklch(0.90 0.11 158)',
  '--green': 'oklch(0.85 0.13 158)',
  '--green-soft': 'rgba(255,255,255,0.14)',
  '--line2': 'rgba(255,255,255,0.24)',
  '--line': 'rgba(255,255,255,0.16)',
  color: '#ffffff',
};
window.BUYER_BG = 'radial-gradient(1100px 640px at 50% -8%, oklch(0.55 0.11 158), oklch(0.40 0.085 158) 64%)';
