// TripTab loader screen — HUD boot sequence
// Logo: hexagonal mark with stacked bars ("tab" rows) scanning into place + Rajdhani wordmark

function LoaderScreen({ ctx }) {
  const [progress, setProgress] = React.useState(0);
  const [statusIdx, setStatusIdx] = React.useState(0);
  const [assembled, setAssembled] = React.useState(false);

  const statuses = [
    'LINKING CREW',
    'SYNC LEDGER',
    'FX RATES · LIVE',
    'VAULT READY',
  ];

  React.useEffect(() => {
    const t = setTimeout(() => setAssembled(true), 900);
    return () => clearTimeout(t);
  }, []);

  React.useEffect(() => {
    const duration = 3200;
    const tickMs = 60;
    const start = Date.now();
    let handedOff = false;
    const iv = setInterval(() => {
      const el = (Date.now() - start) / duration;
      const p = Math.min(1, el);
      setProgress(p);
      setStatusIdx(Math.min(statuses.length - 1, Math.floor(p * statuses.length)));
      if (p >= 1) {
        clearInterval(iv);
        if (!handedOff) {
          handedOff = true;
          setTimeout(() => ctx && ctx.go && ctx.go('home'), 600);
        }
      }
    }, tickMs);
    // Fallback hand-off in case interval is also throttled
    const fallback = setTimeout(() => {
      setProgress(1);
      setStatusIdx(statuses.length - 1);
      if (!handedOff) {
        handedOff = true;
        setTimeout(() => ctx && ctx.go && ctx.go('home'), 600);
      }
    }, duration + 800);
    return () => { clearInterval(iv); clearTimeout(fallback); };
  }, []);

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: '#000',
      overflow: 'hidden',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'var(--font-ui)',
    }}>
      {/* Ambient bg */}
      <div style={{ position: 'absolute', inset: 0, opacity: 0.65 }}>
        <HexBg />
      </div>

      {/* Radial glow behind logo */}
      <div style={{
        position: 'absolute', top: '38%', left: '50%',
        width: 340, height: 340, transform: 'translate(-50%, -50%)',
        background: 'radial-gradient(circle, rgba(59,180,232,0.22), transparent 60%)',
        pointerEvents: 'none',
        filter: 'blur(2px)',
      }} />

      {/* Scan line across the whole screen */}
      <div className="scanline" style={{ top: 0, animationDuration: '3.2s' }} />

      <div style={{ position: 'relative', zIndex: 2, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 28, width: '100%' }}>
        <TripTabMark assembled={assembled} />

        {/* Wordmark */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
          <div style={{
            fontFamily: 'var(--font-display)',
            fontWeight: 700,
            fontSize: 44,
            letterSpacing: '0.04em',
            color: 'var(--text-hi)',
            lineHeight: 1,
            display: 'flex', alignItems: 'baseline', gap: 2,
          }}>
            <span>TRIP</span>
            <span style={{ color: 'var(--cyan-500)' }}>TAB</span>
            <span style={{
              display: 'inline-block',
              width: 10, height: 10,
              background: 'var(--cyan-500)',
              marginLeft: 6,
              boxShadow: '0 0 12px var(--cyan-500)',
              animation: 'blink 1.1s steps(1) infinite',
            }} />
          </div>
          <div style={{
            fontFamily: 'var(--font-display)',
            fontSize: 10,
            letterSpacing: '0.48em',
            color: 'var(--cyan-600)',
            textTransform: 'uppercase',
            fontWeight: 500,
          }}>
            {'// CREW LEDGER PROTOCOL'}
          </div>
        </div>

        {/* Progress rail */}
        <div style={{ width: 240, display: 'flex', flexDirection: 'column', gap: 10, marginTop: 14 }}>
          <div style={{
            position: 'relative',
            height: 3,
            background: 'rgba(59,180,232,0.12)',
            border: '1px solid var(--line)',
            borderRadius: 0,
          }}>
            <div style={{
              position: 'absolute', left: 0, top: 0, bottom: 0,
              width: (progress * 100) + '%',
              background: 'linear-gradient(90deg, var(--cyan-700), var(--cyan-500))',
              boxShadow: '0 0 12px var(--cyan-500)',
              transition: 'width 120ms linear',
            }} />
            {/* Tick marks */}
            {[0.25, 0.5, 0.75].map((t) => (
              <div key={t} style={{
                position: 'absolute', top: -3, bottom: -3, left: (t * 100) + '%',
                width: 1, background: 'var(--cyan-700)',
              }} />
            ))}
          </div>
          <div style={{
            display: 'flex', justifyContent: 'space-between',
            fontFamily: 'JetBrains Mono, ui-monospace, monospace',
            fontSize: 10,
            letterSpacing: '0.08em',
            color: 'var(--text-mu)',
          }}>
            <span style={{ color: 'var(--cyan-500)' }}>{statuses[statusIdx]}</span>
            <span>{String(Math.floor(progress * 100)).padStart(3, '0')}%</span>
          </div>
        </div>
      </div>

      {/* Footer HUD */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 64,
        display: 'flex', justifyContent: 'space-between',
        padding: '0 28px',
        fontFamily: 'JetBrains Mono, ui-monospace, monospace',
        fontSize: 9,
        letterSpacing: '0.16em',
        color: 'var(--text-dim)',
        textTransform: 'uppercase',
      }}>
        <span>v0.4.2 · build 184</span>
        <span>N 45.43° E 10.99°</span>
      </div>

      {/* Corner brackets on the outer frame */}
      <CornerBrackets />
    </div>
  );
}

function TripTabMark({ assembled }) {
  // Hex logo: outer hex outline + 4 stacked bars inside that scan in (rows of a "tab")
  // Bars represent trip entries / ledger rows
  const size = 128;
  const cx = size / 2, cy = size / 2;
  const r = 54; // hex radius
  const hexPath = (() => {
    const pts = [];
    for (let i = 0; i < 6; i++) {
      const a = (Math.PI / 3) * i - Math.PI / 2;
      pts.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]);
    }
    return 'M' + pts.map(p => p.join(',')).join('L') + 'Z';
  })();

  const bars = [
    { y: cy - 26, w: 56, delay: 0 },
    { y: cy - 9,  w: 44, delay: 120 },
    { y: cy + 8,  w: 64, delay: 240 },
    { y: cy + 25, w: 36, delay: 360 },
  ];

  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      {/* Rotating outer ring — ticks */}
      <svg width={size + 36} height={size + 36} viewBox={`0 0 ${size + 36} ${size + 36}`} style={{
        position: 'absolute', top: -18, left: -18,
        animation: 'tripTabSpin 14s linear infinite',
      }}>
        {Array.from({ length: 36 }).map((_, i) => {
          const a = (Math.PI * 2 / 36) * i;
          const cx2 = (size + 36) / 2;
          const cy2 = (size + 36) / 2;
          const rIn = (size / 2) + 10;
          const rOut = rIn + (i % 3 === 0 ? 8 : 4);
          return (
            <line key={i}
              x1={cx2 + rIn * Math.cos(a)} y1={cy2 + rIn * Math.sin(a)}
              x2={cx2 + rOut * Math.cos(a)} y2={cy2 + rOut * Math.sin(a)}
              stroke={i % 3 === 0 ? 'var(--cyan-500)' : 'var(--cyan-700)'}
              strokeWidth="1"
              opacity={i % 3 === 0 ? 0.9 : 0.5}
            />
          );
        })}
      </svg>

      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ position: 'relative' }}>
        <defs>
          <linearGradient id="hexStroke" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="var(--cyan-300)" />
            <stop offset="100%" stopColor="var(--cyan-700)" />
          </linearGradient>
          <clipPath id="hexClip"><path d={hexPath} /></clipPath>
        </defs>

        {/* Hex fill */}
        <path d={hexPath} fill="rgba(10,20,32,0.85)" />
        {/* Inner subtle grid */}
        <g clipPath="url(#hexClip)" opacity="0.35">
          {[0.25, 0.5, 0.75].map((t, i) => (
            <line key={i} x1={0} y1={size * t} x2={size} y2={size * t} stroke="var(--cyan-700)" strokeWidth="0.5" />
          ))}
        </g>
        {/* Hex stroke */}
        <path d={hexPath} fill="none" stroke="url(#hexStroke)" strokeWidth="1.5" />
        {/* Vertex dots */}
        {Array.from({ length: 6 }).map((_, i) => {
          const a = (Math.PI / 3) * i - Math.PI / 2;
          return <circle key={i} cx={cx + r * Math.cos(a)} cy={cy + r * Math.sin(a)} r="2" fill="var(--cyan-500)" />;
        })}

        {/* Bars — ledger rows */}
        <g clipPath="url(#hexClip)">
          {bars.map((b, i) => (
            <rect key={i}
              x={cx - b.w / 2}
              y={b.y - 3}
              width={assembled ? b.w : 0}
              height={6}
              fill={i === 2 ? 'var(--cyan-500)' : 'var(--cyan-700)'}
              opacity={i === 2 ? 1 : 0.85}
              style={{
                transition: `width 420ms cubic-bezier(.2,.8,.2,1) ${b.delay}ms`,
              }}
            />
          ))}
          {/* Leading edge markers */}
          {bars.map((b, i) => (
            <circle key={'d' + i}
              cx={cx - b.w / 2 - 3}
              cy={b.y}
              r="1.5"
              fill="var(--cyan-300)"
              opacity={assembled ? 1 : 0}
              style={{ transition: `opacity 300ms ${b.delay + 200}ms` }}
            />
          ))}

          {/* Scan line inside hex */}
          <rect x="0" y="0" width={size} height="1.5" fill="var(--cyan-500)" opacity="0.9"
            style={{ animation: 'tripTabScan 2.2s ease-in-out infinite' }} />
        </g>
      </svg>

      <style>{`
        @keyframes tripTabSpin { to { transform: rotate(360deg); } }
        @keyframes tripTabScan {
          0% { transform: translateY(10px); opacity: 0; }
          20%, 80% { opacity: 0.9; }
          100% { transform: translateY(118px); opacity: 0; }
        }
      `}</style>
    </div>
  );
}

function CornerBrackets() {
  const b = {
    position: 'absolute', width: 22, height: 22,
    borderColor: 'var(--cyan-500)', borderStyle: 'solid',
  };
  return (
    <>
      <div style={{ ...b, top: 18, left: 18, borderWidth: '1px 0 0 1px' }} />
      <div style={{ ...b, top: 18, right: 18, borderWidth: '1px 1px 0 0' }} />
      <div style={{ ...b, bottom: 18, left: 18, borderWidth: '0 0 1px 1px' }} />
      <div style={{ ...b, bottom: 18, right: 18, borderWidth: '0 1px 1px 0' }} />
    </>
  );
}

Object.assign(window, { LoaderScreen, TripTabMark });
