// Executive Summary view — the hero readiness score is the moment.

const { useState: useStateS, useEffect: useEffectS, useRef: useRefS } = React;

function useCountUp(target, duration = 1400, deps = []) {
  const [v, setV] = useStateS(0);
  useEffectS(() => {
    let raf, start;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setV(Math.round(target * eased));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
    // eslint-disable-next-line
  }, deps);
  return v;
}

function ScoreRing({ value, max = 100, size = 280, stroke = 8 }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const off = c - (value / max) * c;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="score-ring">
      <circle cx={size/2} cy={size/2} r={r} stroke="rgba(10,10,10,0.06)" strokeWidth={stroke} fill="none"/>
      <circle cx={size/2} cy={size/2} r={r} stroke="var(--blue)" strokeWidth={stroke} fill="none"
        strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"
        transform={`rotate(-90 ${size/2} ${size/2})`} style={{transition:'stroke-dashoffset 1400ms cubic-bezier(.2,.7,.2,1)'}}/>
    </svg>
  );
}

function SubscoreBar({ s, delay }) {
  const [w, setW] = useStateS(0);
  useEffectS(() => {
    const t = setTimeout(() => setW(s.value), delay);
    return () => clearTimeout(t);
  }, [s.value, delay]);
  return (
    <div className="subscore">
      <div className="subscore-head">
        <div className="subscore-label">{s.label}</div>
        <div className="subscore-val">{s.value}<span className="subscore-out">/100</span></div>
      </div>
      <div className="subscore-track">
        <div className="subscore-fill" style={{width: w + '%'}}></div>
      </div>
      <div className="subscore-note">{s.note}</div>
    </div>
  );
}

function SummaryView() {
  const r = window.READINESS;
  const score = useCountUp(r.composite, 1400);
  const hours = useCountUp(r.hoursRecoverable, 1600);

  // Labour value: derive hourly rate from annual wage placeholder, animate in $1K increments
  const hourlyRate = r.annualWagePlaceholder / r.fteHoursPerYear;
  const laborTarget = Math.round(r.hoursRecoverable * hourlyRate / 1000);
  const laborK = useCountUp(laborTarget, 1600);
  const laborDisplay = laborK >= 1000
    ? `$${(laborK / 1000).toFixed(1)}M`
    : `$${laborK}K`;

  // FTE capacity: hours / annual FTE hours, animated ×10 for one decimal
  const fteTarget = Math.round(r.hoursRecoverable / r.fteHoursPerYear * 10);
  const fte10 = useCountUp(fteTarget, 1600);
  const fteDisplay = (fte10 / 10).toFixed(1);

  // Admin toggle for illustrative benchmarks — persisted in localStorage for admin sessions
  const [showBenchmarks, setShowBenchmarks] = useStateS(() => {
    if (window.__isAdminSession) {
      try {
        const saved = JSON.parse(localStorage.getItem('linea_admin_prefs') || '{}');
        if (saved.showBenchmarks != null) return saved.showBenchmarks;
      } catch(e) {}
    }
    return false;
  });

  const toggleBenchmarks = () => {
    setShowBenchmarks(v => {
      const next = !v;
      if (window.__isAdminSession) {
        try { localStorage.setItem('linea_admin_prefs', JSON.stringify({ showBenchmarks: next })); } catch(e) {}
      }
      return next;
    });
  };

  return (
    <div className="view summary-view">
      <section className="hero">
        <div className="hero-left">
          <div className="kicker">Composite AI Readiness</div>
          <div className="hero-score-wrap">
            <div className="hero-ring">
              <ScoreRing value={r.composite}/>
              <div className="hero-score-num">
                <span className="serif-num">{score}</span>
                <span className="hero-out">/100</span>
              </div>
            </div>
            <div className="hero-meta">
              <div className="hero-label">{r.heroLabel}</div>
              <div className="hero-phase">
                <div className="hero-phase-label">Recommended phase</div>
                <div className="hero-phase-value">{r.recommendedPhase}</div>
              </div>
              <div className="hero-pos">
                {showBenchmarks && (
                  <div className="hero-pos-row"><span>Cohort percentile</span><b>72nd</b></div>
                )}
                {showBenchmarks && (
                  <div className="hero-pos-row"><span>Mid-market RE benchmark</span><b>58 / 100</b></div>
                )}
                {window.__isAdminSession && (
                  <button
                    className="benchmark-toggle"
                    onClick={toggleBenchmarks}
                  >
                    {showBenchmarks ? 'Hide benchmarks' : 'Show benchmarks'}
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className="hero-right">
          {r.subscores.map((s, i) => (
            <SubscoreBar key={s.key} s={s} delay={400 + i*180}/>
          ))}
        </div>
      </section>

      <section className="kpis">
        <div className="kpi">
          <div className="kpi-k">Annual hours recoverable</div>
          <div className="kpi-v serif-num">{hours.toLocaleString()}</div>
          <div className="kpi-sub">Phase 1–3 roadmap workflows. Full inventory totals {r.totalInventoryHours.toLocaleString()} hrs.</div>
        </div>
        <div className="kpi">
          <div className="kpi-k">Recoverable labour value</div>
          <div className="kpi-v serif-num">{laborDisplay}<span style={{fontSize:'0.4em', verticalAlign:'super', color:'var(--ink-3)', marginLeft:1}}>*</span></div>
          <div className="kpi-sub">*Based on ${Math.round(r.annualWagePlaceholder / 1000)}K annual wage.</div>
        </div>
        <div className="kpi">
          <div className="kpi-k">FTE-equivalent capacity</div>
          <div className="kpi-v serif-num">{fteDisplay}<span className="kpi-unit">FTE</span></div>
          <div className="kpi-sub">Hours freed as a share of one full-time role per year.</div>
        </div>
        <div className="kpi">
          <div className="kpi-k">Roadmap horizon</div>
          <div className="kpi-v serif-num">{r.timelineMonths}<span className="kpi-unit">mo</span></div>
          <div className="kpi-sub">From engagement start to full Phase-1 completion</div>
        </div>
      </section>

      <section className="findings">
        <div className="section-head">
          <div>
            <div className="kicker">Headline findings</div>
            <h2 className="section-title">A strategy memo, in four points.</h2>
          </div>
          <div className="section-meta">Synthesized from 38 interviews, 16 data sources audited, and 11,400+ workflow hours mapped.</div>
        </div>
        <div className="findings-grid">
          {window.FINDINGS.map((f, i) => (
            <article key={f.n} className="finding" style={{animationDelay: (i*120 + 600) + 'ms'}}>
              <div className="finding-n serif-num">{f.n}</div>
              <h3 className="finding-h">{f.headline}</h3>
              <p className="finding-p">{f.detail}</p>
            </article>
          ))}
        </div>
      </section>

      <section className="summary-foot">
        <div className="foot-card">
          <div className="kicker">Where this goes next</div>
          <div className="foot-card-body">
            The three sections that follow are this assessment in working form: every data source we audited, every workflow we mapped, and the prioritized roadmap we recommend.
          </div>
          <div className="foot-card-nav">
            <a className="link-arrow" onClick={() => window.__nav('data')}>Data Readiness <IconArrowRight size={14}/></a>
            <a className="link-arrow" onClick={() => window.__nav('workflows')}>Workflow Inventory <IconArrowRight size={14}/></a>
            <a className="link-arrow" onClick={() => window.__nav('roadmap')}>Execution Roadmap <IconArrowRight size={14}/></a>
          </div>
        </div>
      </section>
    </div>
  );
}

window.SummaryView = SummaryView;
