/* Homepage Platform showcase — a fixed, staggered cluster of compact design cards on the
   left (subtle mouse parallax), with copy on the right that reveals as you scroll. */
const psReduce = typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

function PChip({ icon, title, sub, metric, tone }) {
  const bg = tone ? tone.bg : 'var(--accent-subtle)';
  const fg = tone ? tone.fg : 'var(--blue-600)';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'var(--surface-card)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: '13px 16px' }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 38, height: 38, flexShrink: 0, borderRadius: 'var(--radius-md)', background: bg, color: fg }}>
        <Icon name={icon} size={18} color={fg} />
      </span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: 'block', fontSize: 'var(--text-sm)', fontWeight: 600, whiteSpace: 'nowrap' }}>{title}</span>
        <span style={{ display: 'block', fontSize: 'var(--text-2xs)', color: 'var(--text-tertiary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</span>
      </span>
      {metric && <span className="tnum mono" style={{ fontSize: 'var(--text-sm)', fontWeight: 600, color: metric.color || 'var(--text-primary)', whiteSpace: 'nowrap' }}>{metric.text}</span>}
    </div>
  );
}

function PlatformShowcase() {
  const vw = useVW();
  const isMobile = vw <= 820;
  const items = [
    { num: '01', eyebrow: 'One-click stems', title: 'Confirm a stem in one click.', desc: 'Full nomination, barge, and surveyor booked together — no email chains, no spreadsheets, no missed steps.', bullets: ['Nomination, barge & surveyor in one flow', 'Reuse vessel and supplier presets', 'Track every stem through to delivery'], w: 300, off: 0, Card: () => <PChip icon="check" tone={{ bg: 'var(--success-subtle)', fg: 'var(--green-600)' }} title="Stem #1042 confirmed" sub="Nomination · barge · surveyor" /> },
    { num: '02', eyebrow: 'Fix instantly', title: 'Lock your price the moment it’s right.', desc: 'Hold a price while you decide, then confirm — barge, surveyor, and all — in a single flow.', bullets: ['Lock a price', 'Full nomination and barge details', 'Surveyor booked in-flow'], w: 324, off: 52, Card: () => <PChip icon="lock" title="VLSFO price locked" sub="Singapore" metric={{ text: '$612.50' }} /> },
    { num: '03', eyebrow: 'Pay later', title: 'Settle on your schedule.', desc: 'Draw on a revolving credit line in any port — and settle on Net 30 or Net 60.', bullets: ['Net 30 / 60 / 90 approved', 'Limit per vessel', 'One consolidated invoice per period'], w: 300, off: 16, Card: () => <PChip icon="wallet" title="Net 60 available" sub="Draw anytime" metric={{ text: '$2.40M' }} /> },
    { num: '04', eyebrow: 'Spend analytics', title: 'See every dollar, clearly.', desc: 'Break spend down by vessel, grade, and port, follow the trend month to month, and export in one click.', bullets: ['Spend by vessel, grade, and port', 'Month-to-date and trend views', 'Export to your TMS or accounting'], w: 322, off: 56, Card: () => <PChip icon="bar-chart-3" title="Fleet spend · MTD" sub="Across 6 vessels" metric={{ text: '▲ 6.4%', color: 'var(--green-600)' }} /> },
    { num: '05', eyebrow: 'Worldwide coverage', title: 'Anywhere your fleet sails.', desc: 'We sell and deliver across 100+ ports on six continents — with market pricing local to each region.', bullets: ['100+ ports, six continents', 'Local delivery in every region', 'Live regional pricing'], w: 296, off: 24, Card: () => <PChip icon="globe" title="100+ ports covered" sub="Six continents · live pricing" /> },
    { num: '06', eyebrow: '24/7 support', title: 'Real people, around the clock.', desc: 'A dedicated bunker desk on call 24/7, in every timezone, whenever a stem needs attention.', bullets: ['Dedicated bunker desk', 'Average reply under 5 minutes', 'Claims handled in-platform'], w: 314, off: 48, Card: () => <PChip icon="headset" title="bunkerme desk" sub="Online · ~4 min reply" /> },
  ];
  const [active, setActive] = React.useState(0);
  const textRefs = React.useRef([]);
  const cardRefs = React.useRef([]);

  const Heading = (
    <div style={{ maxWidth: 660, margin: '0 auto', padding: isMobile ? '80px 20px 40px' : '176px 28px 56px', textAlign: 'center' }}>
      <div className="eyebrow" style={{ color: 'var(--blue-600)', marginBottom: 12 }}>Platform</div>
      <h2 style={{ fontSize: 'var(--text-h1)', fontWeight: 600, letterSpacing: 'var(--tracking-tight)', lineHeight: 1.1, marginBottom: 14 }}>The whole stem, one platform</h2>
      <p style={{ fontSize: 'var(--text-lg)', color: 'var(--text-secondary)', lineHeight: 'var(--leading-normal)' }}>From sourcing the right fuel to settling on flexible terms — and the monitoring to keep every vessel moving.</p>
    </div>
  );

  React.useEffect(() => {
    let raf = 0;
    const update = () => {
      raf = 0;
      const vh = window.innerHeight || 800;
      let best = 0, bestD = Infinity;
      textRefs.current.forEach((el, i) => {
        if (!el) return;
        const r = el.getBoundingClientRect();
        const c = r.top + r.height / 2;
        const d = Math.abs(c - vh / 2);
        if (d < bestD) { bestD = d; best = i; }
      });
      setActive((prev) => (prev === best ? prev : best));
    };
    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); if (raf) cancelAnimationFrame(raf); };
  }, []);

  React.useEffect(() => {
    if (psReduce) return;
    const sec = document.getElementById('platform');
    if (!sec) return;
    let raf = 0, tx = 0, ty = 0;
    const apply = () => {
      raf = 0;
      cardRefs.current.forEach((el, i) => { if (el) { const d = 7 + i * 2; el.style.transform = `translate(${(tx * d).toFixed(1)}px, ${(ty * d).toFixed(1)}px)`; } });
    };
    const onMove = (e) => { const r = sec.getBoundingClientRect(); tx = (e.clientX - r.left) / r.width - 0.5; ty = (e.clientY - r.top) / r.height - 0.5; if (!raf) raf = requestAnimationFrame(apply); };
    const onLeave = () => { cardRefs.current.forEach((el) => { if (el) el.style.transform = 'translate(0,0)'; }); };
    sec.addEventListener('mousemove', onMove);
    sec.addEventListener('mouseleave', onLeave);
    return () => { sec.removeEventListener('mousemove', onMove); sec.removeEventListener('mouseleave', onLeave); if (raf) cancelAnimationFrame(raf); };
  }, []);

  if (isMobile) {
    return (
      <section id="platform">
        {Heading}
        <div style={{ maxWidth: 560, margin: '0 auto', padding: '0 20px 72px', display: 'flex', flexDirection: 'column', gap: 44 }}>
          {items.map((it) => (
            <div key={it.num} style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
                <span className="tnum mono" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 34, height: 34, borderRadius: '50%', background: 'var(--blue-500)', color: '#fff', fontSize: 'var(--text-sm)', fontWeight: 600 }}>{it.num}</span>
                <span className="eyebrow" style={{ color: 'var(--blue-600)', whiteSpace: 'nowrap' }}>{it.eyebrow}</span>
              </div>
              <h2 style={{ fontSize: 'var(--text-h2)', fontWeight: 600, letterSpacing: 'var(--tracking-tighter)', lineHeight: 1.1, color: 'var(--text-primary)' }}>{it.title}</h2>
              <div style={{ boxShadow: '0 0 0 1px var(--border-default), 0 10px 26px rgba(17,21,26,0.08)', borderRadius: 'var(--radius-lg)' }}>{it.Card()}</div>
              <p style={{ fontSize: 'var(--text-base)', color: 'var(--text-secondary)', lineHeight: 'var(--leading-normal)' }}>{it.desc}</p>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
                {it.bullets.map((b) => (
                  <li key={b} style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 'var(--text-sm)', color: 'var(--text-secondary)' }}>
                    <span style={{ display: 'inline-flex', width: 22, height: 22, borderRadius: '50%', background: 'var(--success-subtle)', color: 'var(--green-600)', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <Icon name="check" size={14} color="var(--green-600)" />
                    </span>{b}
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </section>
    );
  }

  return (
    <section id="platform">
      <div style={{ maxWidth: 660, margin: '0 auto', padding: '176px 28px 56px', textAlign: 'center' }}>
        <div className="eyebrow" style={{ color: 'var(--blue-600)', marginBottom: 12 }}>Platform</div>
        <h2 style={{ fontSize: 'var(--text-h1)', fontWeight: 600, letterSpacing: 'var(--tracking-tight)', lineHeight: 1.1, marginBottom: 14 }}>The whole stem, one platform</h2>
        <p style={{ fontSize: 'var(--text-lg)', color: 'var(--text-secondary)', lineHeight: 'var(--leading-normal)' }}>From sourcing the right fuel to settling on flexible terms — and the monitoring to keep every vessel moving.</p>
      </div>

      <div style={{ maxWidth: 'var(--container-max)', margin: '0 auto', padding: '0 28px 80px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'start' }}>
        {/* LEFT — fixed staggered cluster of compact designs (mouse parallax) */}
        <div style={{ position: 'sticky', top: 92, height: 'calc(100vh - 92px)', display: 'flex', alignItems: 'center' }}>
          <div style={{ position: 'relative', width: '100%' }}>
            <svg aria-hidden="true" preserveAspectRatio="none" viewBox="0 0 100 600" style={{ position: 'absolute', inset: '-40px 0', width: '100%', height: 'calc(100% + 80px)', zIndex: 0, opacity: 0.5, pointerEvents: 'none' }}>
              <defs>
                <linearGradient id="ps-flow" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="rgba(12,41,241,0)" /><stop offset="20%" stopColor="rgba(80,101,245,0.55)" /><stop offset="80%" stopColor="rgba(12,41,241,0.4)" /><stop offset="100%" stopColor="rgba(12,41,241,0)" />
                </linearGradient>
              </defs>
            </svg>
            <div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', gap: 22 }}>
              {items.map((it, i) => (
                <div key={it.num} ref={(el) => { cardRefs.current[i] = el; }} style={{ width: it.w, marginLeft: it.off, willChange: 'transform', transition: 'transform 220ms var(--ease-out)' }}>
                  <div className={active === i ? 'ps-mark' : ''} style={{ borderRadius: 'var(--radius-lg)', transition: 'opacity 400ms var(--ease-out), transform 320ms var(--ease-out), box-shadow 320ms var(--ease-out)', opacity: active === i ? 1 : 0.46, transform: active === i ? 'scale(1.04)' : 'scale(1)', boxShadow: active === i ? '0 0 0 2px rgba(12,41,241,0.38), 0 14px 34px rgba(17,21,26,0.14)' : 'none' }}>
                    {it.Card()}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* RIGHT — copy that reveals as you scroll */}
        <div>
          {items.map((it, i) => (
            <div key={it.num} data-idx={i} ref={(el) => { textRefs.current[i] = el; }}
              style={{ minHeight: '60vh', display: 'flex', flexDirection: 'column', justifyContent: 'center', opacity: active === i ? 1 : 0.28, transition: 'opacity 450ms var(--ease-out)' }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, marginBottom: 18 }}>
                <span className="tnum mono" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 34, height: 34, borderRadius: '50%', background: 'var(--blue-500)', color: '#fff', fontSize: 'var(--text-sm)', fontWeight: 600 }}>{it.num}</span>
                <span className="eyebrow" style={{ color: 'var(--blue-600)', whiteSpace: 'nowrap' }}>{it.eyebrow}</span>
              </div>
              <h2 style={{ fontSize: 'clamp(2rem, 3vw, 2.75rem)', fontWeight: 600, letterSpacing: 'var(--tracking-tighter)', lineHeight: 1.08, marginBottom: 18, color: 'var(--text-primary)', maxWidth: 460 }}>{it.title}</h2>
              <p style={{ fontSize: 'var(--text-lg)', color: 'var(--text-secondary)', lineHeight: 'var(--leading-normal)', marginBottom: 26, maxWidth: 440 }}>{it.desc}</p>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
                {it.bullets.map((b) => (
                  <li key={b} style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 'var(--text-base)', color: 'var(--text-secondary)' }}>
                    <span style={{ display: 'inline-flex', width: 22, height: 22, borderRadius: '50%', background: 'var(--success-subtle)', color: 'var(--green-600)', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <Icon name="check" size={14} color="var(--green-600)" />
                    </span>{b}
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
      </div>

      <style>{`
        .ps-mark{ animation: psmark 750ms var(--ease-out); }
        @keyframes psmark{ 0%{ box-shadow: 0 0 0 0 rgba(12,41,241,0) } 25%{ box-shadow: 0 0 0 5px rgba(12,41,241,0.22) } 100%{ box-shadow: 0 14px 34px rgba(17,21,26,0.14) } }
        @media (prefers-reduced-motion: reduce){ .ps-mark{ animation: none } }
      `}</style>
    </section>
  );
}

Object.assign(window, { PlatformShowcase });
