// Analyze — Loading screen, lifted verbatim from the app layout exploration.
// Depends on window: RVU, PhoneShell, TabBar.

function sineBump(x0, x1, peak, steps = 16) {
  const out = [];
  for (let i = 1; i <= steps; i++) {
    const t = i / steps;
    const x = x0 + (x1 - x0) * t;
    const y = peak * Math.sin(Math.PI * t);
    out.push([x, y]);
  }
  return out;
}

function makeBeat(xOffset) {
  const off = (pts) => pts.map(([x, y]) => [x + xOffset, y]);
  const pts = [];
  pts.push([0, 0]);
  pts.push([28, 0]);
  pts.push(...sineBump(28, 38, 3, 16));
  pts.push([42, 0]);
  pts.push([46, 0]);
  pts.push([47, -3]);
  pts.push([48, 0]);
  pts.push([50, 42]);
  pts.push([52, -14]);
  pts.push([53, 0]);
  pts.push([58, 0]);
  pts.push(...sineBump(58, 72, 5, 18));
  pts.push([100, 0]);
  return off(pts);
}

function EKG({ width = 360, height = 160, beats = 3, color, dim = '#9CD9D3' }) {
  const totalX = beats * 100;
  const yScale = 1.6;
  const baseY = height * 0.55;

  const pts = [];
  pts.push([0, baseY]);
  for (let i = 0; i < beats; i++) {
    const beat = makeBeat(i * 100);
    beat.forEach(([x, y]) => {
      const px = (x / totalX) * width;
      const py = baseY - y * yScale;
      pts.push([px, py]);
    });
  }
  pts.push([width, baseY]);

  const d = pts.map((p, i) => (i === 0 ? `M${p[0]} ${p[1]}` : `L${p[0]} ${p[1]}`)).join(' ');

  const pathRef = React.useRef(null);
  const [pathLen, setPathLen] = React.useState(0);
  React.useEffect(() => {
    if (pathRef.current) setPathLen(pathRef.current.getTotalLength());
  }, [d]);

  const SWEEP_S = 6;
  const [sweep, setSweep] = React.useState(0);
  React.useEffect(() => {
    let raf;
    const start = performance.now();
    const tick = (t) => {
      const elapsed = (t - start) / 1000;
      const pct = (elapsed % SWEEP_S) / SWEEP_S;
      setSweep(pct);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  let dotX = 0, dotY = baseY;
  if (pathLen && pathRef.current) {
    const pt = pathRef.current.getPointAtLength(sweep * pathLen);
    dotX = pt.x;
    dotY = pt.y;
  }
  const sweepX = sweep * width;

  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ display: 'block', overflow: 'visible' }}>
      <defs>
        <linearGradient id="ekg-trail" x1="0" y1="0" x2="1" y2="0" gradientUnits="objectBoundingBox">
          <stop offset="0%"  stopColor="#fff" stopOpacity="0.85"/>
          <stop offset="100%" stopColor="#fff" stopOpacity="1"/>
        </linearGradient>
        <mask id="trail-mask">
          <rect x="0" y="0" width={Math.max(0, sweepX - 4)} height={height} fill="url(#ekg-trail)"/>
        </mask>
        <filter id="glow" x="-20%" y="-20%" width="140%" height="140%">
          <feGaussianBlur stdDeviation="1.3" result="b"/>
          <feMerge>
            <feMergeNode in="b"/>
            <feMergeNode in="SourceGraphic"/>
          </feMerge>
        </filter>
      </defs>

      <line x1="0" y1={baseY} x2={width} y2={baseY} stroke={dim} strokeWidth="0.6" strokeDasharray="2 3" opacity="0.35"/>

      <path ref={pathRef} d={d} fill="none" stroke={dim} strokeWidth="2" opacity="0.25"
            strokeLinecap="round" strokeLinejoin="round"/>

      <g mask="url(#trail-mask)">
        <path d={d} fill="none" stroke={color} strokeWidth="2.4"
              strokeLinecap="round" strokeLinejoin="round" filter="url(#glow)"/>
      </g>

      <line
        x1={sweepX} y1={6} x2={sweepX} y2={height - 6}
        stroke={color} strokeWidth="1.2" opacity="0.55"
        strokeLinecap="round"
      />
    </svg>
  );
}

function AnalyzeLoading() {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 500);
    return () => clearInterval(id);
  }, []);
  const dots = '.'.repeat((tick % 3) + 1);

  return (
    <PhoneShell>
      <div style={{ padding: '14px 20px 8px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
          <div style={{
            width: 8, height: 8, borderRadius: 999,
            background: RVU.tealDeep,
            boxShadow: `0 0 0 4px ${RVU.teal}22`,
            animation: 'pulse 1.6s ease-in-out infinite',
          }}/>
          <span style={{ fontSize: 11, fontWeight: 600, color: RVU.textSec, letterSpacing: 0.4 }}>
            AI-POWERED BILLING INSIGHTS
          </span>
        </div>
        <div style={{ fontSize: 34, fontWeight: 700, color: RVU.navyDark, letterSpacing: -0.9, lineHeight: 1.05 }}>
          Analyze
        </div>
      </div>

      <div style={{
        flex: 1,
        display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        padding: '36px 24px',
        gap: 18,
      }}>
        <div style={{ width: '100%' }}>
          <EKG width={360} height={170} beats={1} color={RVU.teal}/>
        </div>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '6px 12px', borderRadius: 999,
          background: RVU.surface, border: `1px solid ${RVU.borderLt}`,
          fontFamily: RVU.fontMono, fontSize: 10.5, color: RVU.textSec,
          letterSpacing: 0.4,
        }}>
          <span style={{
            width: 6, height: 6, borderRadius: 999, background: RVU.tealDeep,
            animation: 'pulse 1.6s ease-in-out infinite',
          }}/>
          READING ENCOUNTERS
          <span style={{ color: RVU.textMuted }}>·</span>
          <span style={{ color: RVU.navy, fontWeight: 600 }}>118 / 118</span>
        </div>

        <div style={{ textAlign: 'center', maxWidth: 320 }}>
          <div style={{
            fontSize: 19, fontWeight: 700, color: RVU.navyDark,
            lineHeight: 1.3, letterSpacing: -0.3,
          }}>
            Analyzing your billing patterns{dots}
          </div>
          <div style={{
            fontSize: 13, color: RVU.textSec, marginTop: 10, lineHeight: 1.5,
          }}>
            This usually takes 30–60 seconds. Stay on this screen until complete.
          </div>
        </div>

        <ProgressBar/>
        <Steps/>

        <div style={{
          fontSize: 11.5, color: RVU.textMuted,
          textAlign: 'center', maxWidth: 280, lineHeight: 1.5,
        }}>
          Complex analyses with more encounter data may take longer.
        </div>
      </div>

      <TabBar active="Analyze"/>

      <style>{`
        @keyframes pulse {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.35; }
        }
        @keyframes barFill {
          0% { width: 8%; }
          50% { width: 62%; }
          100% { width: 86%; }
        }
        @keyframes stepBlink {
          0%, 100% { opacity: 0.35; }
          50% { opacity: 1; }
        }
      `}</style>
    </PhoneShell>
  );
}

function ProgressBar() {
  return (
    <div style={{
      width: '88%', maxWidth: 320, height: 4, borderRadius: 999,
      background: RVU.borderLt, overflow: 'hidden', position: 'relative',
    }}>
      <div style={{
        height: '100%', borderRadius: 999,
        background: `linear-gradient(90deg, ${RVU.teal}, ${RVU.tealDeep})`,
        animation: 'barFill 9s ease-in-out infinite',
      }}/>
    </div>
  );
}

function Steps() {
  const steps = [
    { label: 'Indexing encounters',     state: 'done' },
    { label: 'Detecting code patterns', state: 'active' },
    { label: 'Comparing benchmarks',    state: 'pending' },
    { label: 'Drafting insights',       state: 'pending' },
  ];
  return (
    <div style={{ width: '100%', maxWidth: 320, display: 'flex', flexDirection: 'column', gap: 8, marginTop: 4 }}>
      {steps.map(s => (
        <div key={s.label} style={{
          display: 'flex', alignItems: 'center', gap: 10,
          fontSize: 12.5,
          color: s.state === 'pending' ? RVU.textMuted : RVU.navyDark,
          fontWeight: s.state === 'active' ? 600 : 500,
        }}>
          <StepIcon state={s.state}/>
          <span>{s.label}</span>
          {s.state === 'active' && (
            <span style={{
              marginLeft: 'auto', fontFamily: RVU.fontMono,
              fontSize: 10, color: RVU.tealDeep, letterSpacing: 0.5,
              animation: 'stepBlink 1.2s ease-in-out infinite',
            }}>WORKING</span>
          )}
        </div>
      ))}
    </div>
  );
}

function StepIcon({ state }) {
  if (state === 'done') {
    return (
      <span style={{
        width: 16, height: 16, borderRadius: 999, background: RVU.tealDeep,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
      }}>
        <svg width="9" height="9" viewBox="0 0 24 24" fill="none">
          <path d="M5 12l5 5L20 7" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </span>
    );
  }
  if (state === 'active') {
    return (
      <span style={{
        width: 16, height: 16, borderRadius: 999,
        border: `2px solid ${RVU.tealDeep}`, position: 'relative', flexShrink: 0,
      }}>
        <span style={{
          position: 'absolute', inset: 2, borderRadius: 999,
          background: RVU.tealDeep,
          animation: 'pulse 1.2s ease-in-out infinite',
        }}/>
      </span>
    );
  }
  return (
    <span style={{
      width: 16, height: 16, borderRadius: 999,
      border: `2px solid ${RVU.borderLt}`, flexShrink: 0,
    }}/>
  );
}

window.AnalyzeLoading = AnalyzeLoading;
