// ============================================================================
// Hero — fixed-width 1320px composition. Copy column on the left (560px),
// dashboard + collage on the right (760px). Docs are anchored inside the
// right pane only, never crossing into the copy column or top nav zone.
// ============================================================================

const { useEffect, useState, useRef } = React;

function useTickedNumber(target, { duration = 1400, start = target - 1200 } = {}) {
  const [val, setVal] = useState(start);
  useEffect(() => {
    let raf, t0;
    const step = (t) => {
      if (!t0) t0 = t;
      const p = Math.min(1, (t - t0) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(Math.round(start + (target - start) * eased));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [target]);
  return val;
}

// Doc with a gentle drift cycle. x/y are in PIXELS within the right pane.
function DriftDoc({ x, y, rot, scale = 1, delay = 0, drift = 6, z, dim = 0, children }) {
  const style = {
    position: 'absolute',
    left: x, top: y,
    transform: `translate(-50%, -50%) rotate(${rot}deg) scale(${scale})`,
    transformOrigin: 'center',
    zIndex: z,
    animation: `bl-drift ${10 + drift}s ease-in-out ${delay}s infinite alternate`,
    filter: dim ? `brightness(${1 - dim * 0.55}) saturate(${1 - dim * 0.4})` : 'none',
    opacity: 1 - dim * 0.25,
  };
  return <div style={style}>{children}</div>;
}

function Hero({ density, dashboardSize, dashboardSlotFilled }) {
  // Right pane is 760px wide × 720px tall. Dashboard sits centered around
  // (380, 360). Larger product-screen fragments scatter around it — they CAN
  // bleed off all four edges (overflow:hidden clips), as long as enough of
  // each card's identity remains visible.
  //
  // Fragment sizes (intrinsic):
  //   exec        460×~210   compact, dark
  //   orders      540×~280   dense table, dark
  //   returns     580×~350   widest, dark
  //   claim       420×~430   tall, light canvas — anchors a corner
  //   markets     480×~280   light canvas — visual contrast
  const collage = {
    sparse: [
      { kind: 'orders',  x: 110, y: 230, rot: -6, scale: 0.78, z: 1, dim: 0.25, drift: 4 },
      { kind: 'claim',   x: 700, y: 200, rot: 5,  scale: 0.78, z: 1, dim: 0.30, drift: 6 },
      { kind: 'markets', x: 640, y: 580, rot: -3, scale: 0.78, z: 2, dim: 0.12, drift: 3 },
      { kind: 'exec',    x: 120, y: 600, rot: 4,  scale: 0.78, z: 1, dim: 0.35, drift: 5 },
    ],
    balanced: [
      { kind: 'orders',  x: 90,  y: 210, rot: -7, scale: 0.80, z: 1, dim: 0.18, drift: 4 },
      { kind: 'claim',   x: 720, y: 220, rot: 6,  scale: 0.78, z: 1, dim: 0.25, drift: 6 },
      { kind: 'markets', x: 660, y: 600, rot: -4, scale: 0.80, z: 2, dim: 0.10, drift: 3 },
      { kind: 'exec',    x: 100, y: 600, rot: 6,  scale: 0.80, z: 1, dim: 0.30, drift: 5 },
      { kind: 'returns', x: 320, y: 700, rot: -3, scale: 0.70, z: 2, dim: 0.35, drift: 7 },
      { kind: 'exec',    x: 90,  y: 410, rot: 10, scale: 0.62, z: 1, dim: 0.55, drift: 6 },
    ],
    dense: [
      { kind: 'orders',  x: 70,  y: 200, rot: -8, scale: 0.84, z: 1, dim: 0.14, drift: 4 },
      { kind: 'claim',   x: 740, y: 200, rot: 6,  scale: 0.80, z: 1, dim: 0.20, drift: 6 },
      { kind: 'markets', x: 680, y: 600, rot: -4, scale: 0.84, z: 2, dim: 0.08, drift: 3 },
      { kind: 'exec',    x: 80,  y: 610, rot: 7,  scale: 0.84, z: 1, dim: 0.20, drift: 5 },
      { kind: 'returns', x: 320, y: 720, rot: -4, scale: 0.74, z: 2, dim: 0.28, drift: 7 },
      { kind: 'exec',    x: 70,  y: 410, rot: 12, scale: 0.62, z: 1, dim: 0.45, drift: 6 },
      { kind: 'orders',  x: 660, y: 720, rot: 10, scale: 0.58, z: 1, dim: 0.50, drift: 5 },
      { kind: 'markets', x: 60,  y: 130, rot: 9,  scale: 0.56, z: 1, dim: 0.55, drift: 6 },
      { kind: 'claim',   x: 540, y: 110, rot: -9, scale: 0.54, z: 1, dim: 0.55, drift: 7 },
      { kind: 'returns', x: 720, y: 400, rot: 8,  scale: 0.62, z: 1, dim: 0.45, drift: 4 },
    ],
  };
  const items = collage[density] || collage.balanced;

  const renderDoc = (kind) => {
    if (kind === 'exec')    return <ExecutiveSummary/>;
    if (kind === 'orders')  return <OrderExplorer/>;
    if (kind === 'returns') return <ReturnsFragment/>;
    if (kind === 'claim')   return <ClaimPack/>;
    if (kind === 'markets') return <DestinationMarkets/>;
    return null;
  };

  const dashW = dashboardSize === 'full' ? 720 : 560;
  const dashH = dashboardSize === 'full' ? 480 : 380;

  return (
    <section style={{
      position: 'relative',
      background: 'var(--bl-canvas)',
      backgroundImage: [
        'radial-gradient(50% 55% at 70% 50%, rgba(13,158,140,0.18) 0%, rgba(13,158,140,0) 60%)',
        'radial-gradient(120% 70% at 50% 0%, rgba(30,41,59,0.65) 0%, rgba(15,23,42,0) 70%)',
        'linear-gradient(rgba(255,255,255,0.022) 1px, transparent 1px)',
        'linear-gradient(90deg, rgba(255,255,255,0.022) 1px, transparent 1px)',
      ].join(','),
      backgroundSize: 'auto, auto, 64px 64px, 64px 64px',
      overflow: 'hidden',
      paddingTop: 20,
      paddingBottom: 60,
    }}>
      <style>{`
        @keyframes bl-drift {
          0%   { transform: translate(-50%, -50%) rotate(var(--r, 0deg)) scale(var(--s, 1)) translateY(0); }
          100% { transform: translate(-50%, -50%) rotate(var(--r, 0deg)) scale(var(--s, 1)) translateY(-6px); }
        }
        @keyframes bl-fade-in {
          from { opacity: 0; transform: translateY(8px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes bl-pulse {
          0%, 100% { box-shadow: 0 0 0 3px rgba(13,158,140,0.18); }
          50%      { box-shadow: 0 0 0 5px rgba(13,158,140,0.32); }
        }
        .bl-fade-1 { animation: bl-fade-in 0.7s ease-out 0.0s both; }
        .bl-fade-2 { animation: bl-fade-in 0.7s ease-out 0.15s both; }
        .bl-fade-3 { animation: bl-fade-in 0.7s ease-out 0.30s both; }
        .bl-fade-4 { animation: bl-fade-in 0.8s ease-out 0.50s both; }
        .bl-cta-primary:hover { background: #14b8a6; }
        .bl-link:hover { color: #14b8a6; }
      `}</style>

      {/* Two-column composition, fixed widths */}
      <div style={{
        position: 'relative',
        width: 1320, margin: '0 auto',
        display: 'grid',
        gridTemplateColumns: '500px 720px',
        gap: 44,
        alignItems: 'start',
        paddingLeft: 56,
        boxSizing: 'border-box',
      }}>
        {/* Copy column */}
        <div style={{ paddingTop: 40, position: 'relative', zIndex: 5 }}>
          <div className="bl-fade-1" style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            fontSize: 11, fontWeight: 600,
            color: 'var(--bl-brand-hi)',
            textTransform: 'uppercase', letterSpacing: '0.14em',
            padding: '6px 12px',
            border: '1px solid var(--bl-brand-border)',
            background: 'var(--bl-brand-bg)',
            borderRadius: 999,
            marginBottom: 28,
          }}>
            <span style={{
              width: 7, height: 7, borderRadius: '50%', background: 'var(--bl-brand)',
              boxShadow: '0 0 0 3px rgba(13,158,140,0.18)',
              animation: 'bl-pulse 2.4s ease-in-out infinite',
            }}/>
            Live · End-to-end cross-border visibility
          </div>
          <h1 className="bl-fade-1" style={{
            fontSize: 52, lineHeight: 1.05, fontWeight: 600,
            color: 'var(--bl-text-0)', letterSpacing: '-0.025em',
            margin: 0, fontFamily: 'var(--bl-font)',
            maxWidth: 450,
            textWrap: 'pretty',
          }}>
            One platform. Every cross-border cost, variance, reconciliation and recovery opportunity.
          </h1>
          <p className="bl-fade-3" style={{
            fontSize: 16, lineHeight: 1.55, color: 'var(--bl-text-2)',
            margin: '24px 0 0', maxWidth: 480,
          }}>
            Whatever your incoterms or volume, BorderLens gives you complete visibility — from checkout duty collection to CDS declarations to carrier billing.
          </p>
          <div className="bl-fade-3" style={{ display: 'flex', alignItems: 'center', gap: 20, marginTop: 36 }}>
            <a href="mailto:hello@borderlens.io?subject=BorderLens%20demo" className="bl-cta-primary" style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              background: 'var(--bl-brand)', color: '#042f2e',
              fontSize: 14, fontWeight: 600, padding: '12px 22px',
              borderRadius: 8, transition: 'background 0.15s',
            }}>Book a demo <Icon.Arrow size={14}/></a>
            <a href="/guides" className="bl-link" style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              fontSize: 14, fontWeight: 500, color: 'var(--bl-text-2)',
              transition: 'color 0.15s',
            }}>Read the guides <span style={{ opacity: 0.5 }}>→</span></a>
          </div>
          <div className="bl-fade-4" style={{ marginTop: 48, paddingTop: 24, borderTop: '1px solid var(--bl-surface-2)' }}>
            <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--bl-text-4)', textTransform: 'uppercase', letterSpacing: '0.14em', marginBottom: 14 }}>Reconciles</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {['Carrier invoices','CDS declarations','Shopify exports','Rate cards','Product data'].map((label) => (
                <span key={label} style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  fontSize: 11.5, fontWeight: 500, color: 'var(--bl-text-2)',
                  padding: '5px 10px', background: 'rgba(30,41,59,0.6)',
                  border: '1px solid var(--bl-surface-2)', borderRadius: 6,
                  fontFamily: 'var(--bl-font-mono)',
                }}>
                  <span style={{ color: 'var(--bl-text-4)' }}><Icon.Doc size={11}/></span>
                  {label}
                </span>
              ))}
            </div>
          </div>
        </div>

        {/* Right pane — collage + dashboard */}
        <div style={{ position: 'relative', width: 760, height: 720 }}>
          {items.map((it, i) => (
            <DriftDoc key={`${it.kind}-${i}`} x={it.x} y={it.y} rot={it.rot} scale={it.scale} z={it.z} dim={it.dim} drift={it.drift} delay={i * 0.4}>
              {renderDoc(it.kind)}
            </DriftDoc>
          ))}
          <div style={{
            position: 'absolute', left: 380, top: 360,
            transform: 'translate(-50%, -50%)', zIndex: 10,
          }} className="bl-fade-4">
            <DashboardCard density={dashboardSize} tickedTotal={127405}/>
          </div>
        </div>
      </div>

      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, height: 160,
        background: 'linear-gradient(to bottom, rgba(15,23,42,0) 0%, var(--bl-canvas) 100%)',
        pointerEvents: 'none', zIndex: 15,
      }}/>
    </section>
  );
}

window.Hero = Hero;
