// Landing chooser — split-screen with bokeh particles (left) + node network (right)
// Center wordmark: TAKTUME with ANYTIME pop on left half, Recruit pop on right half

const AnytimeMarkA = window.AnytimeMarkA;
const RecruitMarkF = window.RecruitMarkF;

const ChooserArrow = () => (
  <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
    <path d="M3 8h10M9 4l4 4-4 4" />
  </svg>
);

// ─── Bokeh particle canvas (Anytime side) — copied & adapted from existing brand
function BokehCanvas({ side = 'left', accent = 'purple' }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const c = ref.current; if (!c) return;
    const ctx = c.getContext('2d');
    let W, H, blobs = [], raf;
    const COLS = accent === 'purple'
      ? [[270,70,58],[280,65,55],[260,60,60],[290,55,57],[300,50,55],[200,60,58],[195,75,60],[0,0,78]]
      : [[180,80,55],[190,75,55],[200,70,58],[170,60,55],[185,80,60],[0,0,78]];
    function resize(){ W = c.width = c.offsetWidth; H = c.height = c.offsetHeight; }
    function mk(){
      const col = COLS[Math.floor(Math.random()*COLS.length)];
      return {
        x: Math.random()*W, y: Math.random()*H,
        r: Math.random()*30 + 10,
        vx: (Math.random()-.5)*.17, vy: (Math.random()-.5)*.13,
        a: Math.random()*.45 + .22,
        h: col[0], s: col[1], l: col[2],
        w: Math.random()*Math.PI*2, ws: Math.random()*.005 + .002,
      };
    }
    function init(){ resize(); blobs = Array.from({length: 56}, mk); }
    function draw(){
      ctx.clearRect(0, 0, W, H);
      blobs.forEach(b => {
        b.w += b.ws;
        b.x += b.vx + Math.sin(b.w)*.14;
        b.y += b.vy + Math.cos(b.w*.8)*.1;
        if (b.x < -70) b.x = W + 70;
        if (b.x > W + 70) b.x = -70;
        if (b.y < -70) b.y = H + 70;
        if (b.y > H + 70) b.y = -70;
        const g = ctx.createRadialGradient(b.x, b.y, 0, b.x, b.y, b.r*3.8);
        const col = b.s === 0
          ? `rgba(205,195,225,${b.a})`
          : `hsla(${b.h},${b.s}%,${b.l}%,${b.a})`;
        g.addColorStop(0, col);
        g.addColorStop(1, `hsla(${b.h},${b.s}%,${b.l}%,0)`);
        ctx.beginPath(); ctx.arc(b.x, b.y, b.r*3.8, 0, Math.PI*2);
        ctx.fillStyle = g; ctx.fill();
      });
      raf = requestAnimationFrame(draw);
    }
    init(); draw();
    const onR = () => init();
    window.addEventListener('resize', onR);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', onR); };
  }, [accent]);
  return <canvas ref={ref} className="bokeh-canvas" />;
}

// ─── Node network (Recruit side) — clean, animated, not noisy
function NodeNetwork() {
  const nodes = React.useMemo(() => {
    // 14 well-spaced nodes
    const seed = [
      [18, 30], [32, 22], [50, 28], [68, 24], [82, 32],
      [22, 50], [44, 46], [60, 52], [78, 50],
      [18, 72], [36, 70], [54, 74], [72, 68], [86, 76],
    ];
    return seed.map(([x, y], i) => ({ x, y, k: i, d: 0.1 + i * 0.18 }));
  }, []);
  // edges: connect each node to its 1-2 nearest neighbors
  const edges = React.useMemo(() => {
    const out = [];
    nodes.forEach((a, i) => {
      const dists = nodes
        .map((b, j) => ({ j, d: Math.hypot(a.x - b.x, a.y - b.y) }))
        .filter(x => x.j !== i)
        .sort((p, q) => p.d - q.d);
      out.push({ a: i, b: dists[0].j });
      if (dists[1].d < 30) out.push({ a: i, b: dists[1].j });
    });
    return out;
  }, [nodes]);
  return (
    <svg className="node-net" viewBox="0 0 100 100" preserveAspectRatio="none">
      {edges.map((e, i) => {
        const a = nodes[e.a], b = nodes[e.b];
        return (
          <line
            key={i}
            x1={a.x} y1={a.y} x2={b.x} y2={b.y}
            stroke="rgba(0,255,255,0.18)" strokeWidth="0.18"
            style={{ animation: `netLineIn 1.4s ease ${i * 0.05 + 0.3}s both` }}
          />
        );
      })}
      {nodes.map(n => (
        <g key={n.k} style={{ animation: `netNodeIn 0.6s ease ${n.d}s both` }}>
          <circle cx={n.x} cy={n.y} r="2.2" fill="rgba(0,255,255,0.06)" stroke="rgba(0,255,255,0.4)" strokeWidth="0.3" />
          <circle cx={n.x} cy={n.y} r="0.7" fill="#00FFFF">
            <animate attributeName="opacity" values="0.6;1;0.6" dur={`${2 + Math.random()}s`} repeatCount="indefinite" />
          </circle>
          <circle cx={n.x} cy={n.y} r="2.2" fill="none" stroke="#00FFFF" strokeWidth="0.2" opacity="0">
            <animate attributeName="r" values="2;5;7" dur="2.4s" begin={`${n.d}s`} repeatCount="indefinite" />
            <animate attributeName="opacity" values="0.5;0.1;0" dur="2.4s" begin={`${n.d}s`} repeatCount="indefinite" />
          </circle>
        </g>
      ))}
    </svg>
  );
}

// ─── Hover video reel (4 floating clips slide in sequentially) ───
// Anytime side: feature-themed clips slide in left→right with captions.
// Recruit side: live interview clips slide in right→left, no caption.
// Standalone-aware resolver: when bundled offline, real URLs come from window.__resources.
function _vurl(stem) {
  if (typeof window !== 'undefined' && window.__resources && window.__resources[stem]) {
    return window.__resources[stem];
  }
  return `videos/${stem}.mp4`;
}

const ANYTIME_REEL = [
  { src: _vurl('anytime-jd-tailored'),  cap: 'Resume + JD → personalized interview',     tag: 'JD-TAILORED' },
  { src: _vurl('anytime-coding'),       cap: 'FAANG-style coding, auto-graded live',     tag: 'LIVE CODING' },
  { src: _vurl('anytime-mmi'),          cap: 'Med MMI circuit · 6 stations · real timer', tag: 'MMI' },
  { src: _vurl('anytime-gamification'), cap: '30-day streaks · XP, badges, levels',      tag: 'STREAK' },
];

const RECRUIT_POOL = [
  { src: _vurl('candidate-1'), tag: 'LIVE', cap: 'Senior Backend Engineer · Toronto' },
  { src: _vurl('candidate-2'), tag: 'LIVE', cap: 'Product Designer · London' },
  { src: _vurl('candidate-3'), tag: 'LIVE', cap: 'Sales Engineer · São Paulo' },
  { src: _vurl('candidate-4'), tag: 'LIVE', cap: 'Data Scientist · Tokyo' },
  { src: _vurl('candidate-5'), tag: 'LIVE', cap: 'Frontend Engineer · San Francisco' },
];

function pickRandom(pool, n) {
  const a = [...pool];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a.slice(0, n);
}

function HoverVideoReel({ side }) {
  // Re-pick recruit clips on every mount so they feel "live".
  const recruitClips = React.useMemo(
    () => pickRandom(RECRUIT_POOL, 4),
    []
  );
  const clips = side === 'anytime' ? ANYTIME_REEL : recruitClips;
  return (
    <div className={`hvr hvr-${side}`} aria-hidden="true">
      {clips.map((c, i) => (
        <div
          key={`${side}-${i}`}
          className={`hvr-item hvr-item-${i}`}
          style={{ animationDelay: `${80 + i * 130}ms` }}
        >
          <div className="hvr-card">
            <video
              src={c.src}
              autoPlay
              muted
              loop
              playsInline
              preload="auto"
            />
            <div className="hvr-card-glow"></div>
            {c.tag && <div className="hvr-tag">{c.tag}</div>}
          </div>
          {c.cap && (
            <div className="hvr-cap">{c.cap}</div>
          )}
        </div>
      ))}
    </div>
  );
}

// ─── Center wordmark (always visible). Halves emphasize different sides on hover.
function ChooserWordmark({ activeSide }) {
  return (
    <div className={`chooser-wordmark ${activeSide ? 'side-' + activeSide : ''}`}>
      <span className="wm-anytime">ANYTIME</span>
      <span className="wm-bar"></span>
      <span className="wm-tak">TAKTUME</span>
      <span className="wm-bar"></span>
      <span className="wm-recruit">RECRUIT</span>
    </div>
  );
}

function LandingChooser({ onChoose }) {
  const [hoverSide, setHoverSide] = React.useState(null);
  return (
    <div className={`chooser ${hoverSide ? 'has-hover hover-' + hoverSide : ''}`}>
      {/* persistent backgrounds */}
      <div className="chooser-bg-anytime">
        <BokehCanvas accent="purple" />
      </div>
      <div className="chooser-bg-recruit">
        {/* node network removed per request */}
      </div>

      {/* hover-only video reels — re-mount on each enter so animations replay */}
      {hoverSide === 'anytime' && <HoverVideoReel key="reel-a" side="anytime" />}
      {hoverSide === 'recruit' && <HoverVideoReel key="reel-r" side="recruit" />}

      {/* center wordmark */}
      <ChooserWordmark activeSide={hoverSide} />

      <div className="chooser-question">Which side are you on?</div>

      <div
        className="chooser-half anytime"
        onClick={() => onChoose('anytime')}
        onMouseEnter={() => setHoverSide('anytime')}
        onMouseLeave={() => setHoverSide(null)}
        role="button" tabIndex={0}
      >
        <div className="chooser-content">
          <div className="chooser-mark">
            <AnytimeMarkA size={56} />
          </div>
          <h1 className="chooser-h1">I'm <em>looking for a job.</em></h1>
          <p className="chooser-sub">
            Practice the real conversation before you have it. An AI interviewer trained on the role you actually applied to.
          </p>
          <button className="chooser-cta">
            Start practicing free <ChooserArrow />
          </button>
        </div>
      </div>

      <div
        className="chooser-half recruit"
        onClick={() => onChoose('recruit')}
        onMouseEnter={() => setHoverSide('recruit')}
        onMouseLeave={() => setHoverSide(null)}
        role="button" tabIndex={0}
      >
        <div className="chooser-content">
          <div className="chooser-mark">
            <RecruitMarkF size={56} />
          </div>
          <h1 className="chooser-h1">I'm <em>hiring at scale.</em></h1>
          <p className="chooser-sub">
            Post the JD at 5pm. Open a scored shortlist at 9am. Recruit interviews every qualified candidate, in parallel, overnight.
          </p>
          <button className="chooser-cta">
            Book a 20-min demo <ChooserArrow />
          </button>
        </div>
      </div>

      <div className="chooser-divider">
        <div className="chooser-divider-orb"></div>
      </div>
    </div>
  );
}

window.LandingChooser = LandingChooser;
window.NodeNetwork = NodeNetwork;
window.BokehCanvas = BokehCanvas;
