/* ELC Dashboard — Pipeline, Retention, Marketing, Snapshot */

// ─── Pipeline ───────────────────────────────
function PipelineView() {
  const P = DATA.admissions.pipeline;
  const f = P.funnel;
  const stages = [
    { k: "leads", lbl: "Total leads", v: f.leads.value, d: f.leads.yoyDelta },
    { k: "qual",  lbl: "Qualified leads", v: f.qualifiedLeads.value, d: f.qualifiedLeads.yoyDelta },
    { k: "tours", lbl: "Tours", v: f.tours.value, d: f.tours.yoyDelta },
    { k: "enrol", lbl: "Enrolments", v: f.enrolments.value, d: f.enrolments.yoyDelta },
  ];
  const cr = P.conversionRates;
  const months = P.toursByCampus.map(r => r.m);

  return (
    <div className="view">
      <div className="view-hd">
        <div>
          <h2>Admissions Pipeline <span className="scope-tag">Group · 2025–26</span></h2>
          <p>The funnel feeding future enrolments. Optimise for qualified leads — total leads are easy to move, qualified are what's hard.</p>
        </div>
      </div>

      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card-head">
          <div><h3>Pipeline funnel</h3><div className="sub">As of {P.asOf}. YoY delta on each stage.</div></div>
        </div>
        <div className="funnel">
          {stages.map((s, i) => (
            <div key={s.k} className="fun-stage">
              <div className="lbl">{s.lbl}</div>
              <div className="v">{s.v}</div>
              <div className="d"><span className={`d-mini ${s.d > 0 ? "pos" : s.d < 0 ? "neg" : "neu"}`}>{s.d > 0 ? "+" : ""}{s.d}% YoY</span></div>
              {i < stages.length - 1 && <div className="fun-arrow">›</div>}
            </div>
          ))}
        </div>
        <div className="conv-row">
          <div className="cv"><b>{cr.leadToQualified}%</b>lead → qualified</div>
          <div className="cv"><b>{cr.qualifiedToTour}%</b>qualified → tour</div>
          <div className="cv"><b>{cr.tourToEnrolment}%</b>tour → enrolment</div>
          <div className="cv overall"><b>{cr.overall}%</b>overall</div>
        </div>
      </div>

      <div className="grid c2">
        <div className="card">
          <div className="card-head">
            <div><h3>Monthly tours by campus</h3><div className="sub">Stacked, 9 months</div></div>
            <div className="legend">
              <span className="sw cs">City School</span>
              <span className="sw pe">Purple Elephant</span>
              <span className="sw dc">Dove Centre</span>
            </div>
          </div>
          <StackedBar
            rows={P.toursByCampus}
            keys={["cs", "pe", "dc"]}
            colors={["#7d639b", "#AC9D71", "#4D83C3"]}
            labels={months}
          />
        </div>
        <div className="card">
          <div className="card-head">
            <div><h3>Qualified leads by campus</h3><div className="sub">Stacked, 9 months</div></div>
            <div className="legend">
              <span className="sw cs">City School</span>
              <span className="sw pe">Purple Elephant</span>
              <span className="sw dc">Dove Centre</span>
            </div>
          </div>
          <StackedBar
            rows={P.qualifiedByCampus}
            keys={["cs", "pe", "dc"]}
            colors={["#7d639b", "#AC9D71", "#4D83C3"]}
            labels={months}
          />
        </div>
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <h3>Conversion rates, stage by stage</h3>
        <div className="sub">Where the leaks are</div>
        <table className="dt" style={{ marginTop: 10 }}>
          <thead>
            <tr><th>Stage</th><th className="num">Rate</th><th>Benchmark</th><th>Note</th></tr>
          </thead>
          <tbody>
            <tr><td>Lead → Qualified</td><td className="num">{cr.leadToQualified}%</td><td className="muted">40–50%</td><td className="muted">Mel/Ween first contact + fit screen</td></tr>
            <tr><td>Qualified → Tour</td><td className="num">{cr.qualifiedToTour}%</td><td className="muted">60–70%</td><td className="muted">Tour speed is the main lever</td></tr>
            <tr><td>Tour → Enrolment</td><td className="num">{cr.tourToEnrolment}%</td><td className="muted">50–60%</td><td className="muted">Open House attendees close in 21 days (median)</td></tr>
            <tr><td><b>Overall</b></td><td className="num"><b>{cr.overall}%</b></td><td className="muted">12–18%</td><td className="muted">System-level efficiency</td></tr>
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── Retention ──────────────────────────────
function RetentionView({ narratives, setNarratives, editable }) {
  const R = DATA.retention;
  const trend = R.threeYearTrend;

  return (
    <div className="view">
      <div className="view-hd">
        <div>
          <h2>Retention <span className="scope-tag">Group · applied-out tracking</span></h2>
          <p>Families who have applied to other schools. Weekly cadence Mar–Aug; Jem's narrative replaces the old 5-page email.</p>
        </div>
      </div>

      <div className="grid c4" style={{ marginBottom: 16 }}>
        <div className="kpi"><div className="lbl">Applied out</div><div className="val">{R.totalAppliedOut}</div><div className="foot"><span className="d-mini neu">+4 vs 140 last yr</span></div></div>
        <div className="kpi"><div className="lbl">Confirmed leaving</div><div className="val">{R.confirmedLeaving}</div><div className="foot"><span className="d-mini pos">−61 vs 2023–24</span></div></div>
        <div className="kpi"><div className="lbl">Forced moves</div><div className="val">{R.forced}</div><div className="foot"><span style={{ color: "var(--muted)" }}>relocation, visa, etc.</span></div></div>
        <div className="kpi"><div className="lbl">Unforced leavers</div><div className="val">{R.unforcedLeaving}</div><div className="foot"><span style={{ color: "var(--orange)" }}>chose another Bangkok school</span></div></div>
      </div>

      <div className="card" style={{ marginBottom: 16 }}>
        <div className="card-head">
          <div><h3>3-year applied-out trend</h3><div className="sub">Cumulative, July → June. This year tracking closely to last.</div></div>
          <div className="legend">
            <span className="sw y2324" style={{ color: "var(--hair-strong)" }}>2023–24</span>
            <span className="sw y2425" style={{ color: "var(--purple-light)" }}>2024–25</span>
            <span className="sw y2526" style={{ color: "var(--purple)" }}>2025–26</span>
          </div>
        </div>
        <LineChart
          labels={trend.map(r => r.m)}
          series={[
            { data: trend.map(r => r.y2324), color: "#D4D2CA", width: 1.5, dash: "4,3" },
            { data: trend.map(r => r.y2425), color: "#a086be", width: 2 },
            { data: trend.map(r => r.y2526), color: "#7d639b", width: 2.5, dotR: 3.5 },
          ]}
          height={260}
        />
      </div>

      <div className="grid cs-1-2">
        <div className="card">
          <div className="card-head">
            <div><h3>By year level</h3><div className="sub">Forced vs unforced leavers</div></div>
            <div className="legend">
              <span className="sw forced">Forced</span>
              <span className="sw unforced">Unforced</span>
            </div>
          </div>
          <HBarStack
            rows={R.yearLevels}
            keys={["leftForced", "leftUnforced"]}
            colors={["#39393B", "#B8564A"]}
            labels={R.yearLevels.map(y => y.year)}
            height={220}
          />
        </div>

        <div className="card">
          <div className="card-head">
            <div><h3>Top 5 destinations · 3-year applied vs accepted</h3><div className="sub">Light bar = applied. Dark overlay = accepted.</div></div>
          </div>
          <div>
            {R.destinations.map(d => (
              <DestRow key={d.school} d={d} />
            ))}
          </div>
          <div className="nist-break">
            <span><b>NIST Kindergarten concentration:</b></span>
            <span>K1 · {R.destinations[0].nistBreakdown.K1}</span>
            <span>K2 · {R.destinations[0].nistBreakdown.K2}</span>
            <span>Y1 · {R.destinations[0].nistBreakdown.Y1}</span>
            <span>Y2 · {R.destinations[0].nistBreakdown.Y2}</span>
          </div>
        </div>
      </div>

      <div className="sec-hd"><h3>Retention narrative</h3><span className="sub">Jem Wright</span></div>
      <Narrative k="retention" author="Jem Wright" role="Head of Pastoral Care and Community" color="blue" data={narratives.retention} onChange={(t)=>setNarratives(n=>({...n,retention:{...n.retention,text:t}}))} editable={editable} />
    </div>
  );
}

function DestRow({ d }) {
  const maxApp = 60;
  return (
    <div className="dest-row">
      <div className="name">{d.school}</div>
      <div className="bars">
        {[
          { year: "23/24", app: d.app2324, acc: d.acc2324, grey: true },
          { year: "24/25", app: d.app2425, acc: d.acc2425, gold: true },
          { year: "25/26", app: d.app2526, acc: d.acc2526 },
        ].map(y => (
          <div className="b" key={y.year}>
            <span>{y.year}</span>
            <div className="b-track">
              <span className={`b-fill-app ${y.grey ? "grey" : y.gold ? "gold" : ""}`} style={{ width: (y.app / maxApp * 100) + "%" }} />
              <span className={`b-fill-acc ${y.grey ? "grey" : y.gold ? "gold" : ""}`} style={{ width: (y.acc / maxApp * 100) + "%" }} />
            </div>
            <span style={{ fontVariantNumeric: "tabular-nums", color: "var(--muted)", fontSize: 10.5 }}>{y.acc}/{y.app}</span>
          </div>
        ))}
      </div>
      <div className="totals"><b>{d.acc2526}</b><br/><span>acc this yr</span></div>
    </div>
  );
}

// ─── Marketing ──────────────────────────────
function MarketingView({ narratives, setNarratives, editable }) {
  const M = DATA.marketing;
  const months = M.costPerEnrolment.trend.map(r => r.m);

  return (
    <div className="view">
      <div className="view-hd">
        <div>
          <h2>Marketing efficiency <span className="scope-tag">Target instrumentation</span></h2>
          <p>System-level efficiency + directional insights. Attribution is imperfect; focus is on blended levers.</p>
        </div>
      </div>

      <div className="grid c3" style={{ marginBottom: 16 }}>
        <div className="kpi accent-gold">
          <div className="lbl">Cost per enrolment (blended)</div>
          <div className="val">฿{(M.costPerEnrolment.current/1000).toFixed(1)}k</div>
          <div className="foot"><span>last month ฿{(M.costPerEnrolment.lastMonth/1000).toFixed(1)}k</span><span className="d-mini pos">−5%</span></div>
          <Sparkline data={M.costPerEnrolment.trend} accent="gold" />
        </div>
        <div className="kpi">
          <div className="lbl">Cost per lead</div>
          <div className="val">฿{M.costPerLead.current.toLocaleString()}</div>
          <div className="foot"><span>trending flat</span></div>
          <Sparkline data={M.costPerLead.trend} />
        </div>
        <div className="kpi">
          <div className="lbl">Cost per qualified lead</div>
          <div className="val">฿{M.costPerQualifiedLead.current.toLocaleString()}</div>
          <div className="foot"><span>target metric — Federico</span></div>
          <Sparkline data={M.costPerQualifiedLead.trend} />
        </div>
      </div>

      <div className="grid c2" style={{ marginBottom: 16 }}>
        <div className="card">
          <div className="card-head">
            <div><h3>Cost per enrolment · 9-month trend</h3><div className="sub">Down from ฿51.4k in Aug as paid mix matures</div></div>
          </div>
          <LineChart
            labels={months}
            series={[{ data: M.costPerEnrolment.trend.map(r => r.v), color: "#AC9D71", width: 2.5, dotR: 3.5 }]}
            height={220}
            yFmt={(v) => "฿" + (v/1000).toFixed(0) + "k"}
          />
        </div>

        <div className="card">
          <div className="card-head">
            <div><h3>CPL vs CPQL</h3><div className="sub">CPQL is the lever — qualified leads are what's hard</div></div>
            <div className="legend">
              <span className="sw" style={{ color: "#7d639b" }}>CPL</span>
              <span className="sw" style={{ color: "#AC9D71" }}>CPQL</span>
            </div>
          </div>
          <DualLine
            labels={months}
            a={M.costPerLead.trend.map(r => r.v)}
            b={M.costPerQualifiedLead.trend.map(r => r.v)}
            aColor="#7d639b" bColor="#AC9D71"
          />
        </div>
      </div>

      <div className="grid cs-1-2" style={{ marginBottom: 16 }}>
        <div className="card">
          <div className="card-head">
            <div><h3>Channel contribution</h3><div className="sub">% of leads vs % of enrolments</div></div>
          </div>
          {M.channelContribution.map(c => (
            <div key={c.channel} className="pct-row">
              <div className="nm">{c.channel}</div>
              <div className="pct-bar leads"><span>leads</span><div className="track"><span style={{ width: c.leads + "%" }} /></div><b>{c.leads}%</b></div>
              <div className="pct-bar enrol"><span>enrol</span><div className="track"><span style={{ width: c.enrol + "%" }} /></div><b>{c.enrol}%</b></div>
            </div>
          ))}
          <div className="callout gold" style={{ marginTop: 12 }}>
            Referral converts 28% of leads into 41% of enrolments — brand strength showing up in exit conversations.
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div><h3>Paid channels · for optimisation</h3><div className="sub">Where we're spending right now</div></div>
          </div>
          <table className="dt">
            <thead><tr><th>Channel</th><th className="num">Leads</th><th className="num">CPL</th><th>Qualified rate</th></tr></thead>
            <tbody>
              {M.paidChannels.map(c => (
                <tr key={c.channel}>
                  <td><b>{c.channel}</b></td>
                  <td className="num">{c.leads}</td>
                  <td className="num">฿{c.cpl.toLocaleString()}</td>
                  <td>
                    <span className="mini-bar"><span style={{ width: c.qualRate + "%", background: c.qualRate >= 50 ? "var(--green)" : c.qualRate >= 40 ? "var(--gold)" : "var(--orange)" }} /></span>
                    <span style={{ marginLeft: 8, fontSize: 12, color: "var(--muted)" }}>{c.qualRate}%</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="sec-hd"><h3>Lighthouse instrumentation <span className="tag">target state</span></h3><span className="sub">Metrics the marketing function is being built toward</span></div>
      <div className="grid c2" style={{ marginBottom: 16 }}>
        <div className="card">
          <h3>Top creatives by cost per lead</h3>
          <div className="sub">Meta + Google Ads · this month</div>
          <table className="dt" style={{ marginTop: 10 }}>
            <thead><tr><th>Creative</th><th>Channel</th><th className="num">Leads</th><th className="num">CPL</th></tr></thead>
            <tbody>
              {M.topCreatives.slice(0, 5).map((c, i) => (
                <tr key={i}>
                  <td style={{ maxWidth: 260 }}>{c.creative}</td>
                  <td><span className="chip">{c.channel}</span></td>
                  <td className="num">{c.leads}</td>
                  <td className="num">฿{c.cpl.toLocaleString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card">
          <h3>Event attribution</h3>
          <div className="sub">Open houses + parent experiences</div>
          <table className="dt" style={{ marginTop: 10 }}>
            <thead><tr><th>Event</th><th className="num">Att.</th><th className="num">Tours</th><th className="num">Enrol</th><th className="num">Rate</th></tr></thead>
            <tbody>
              {M.eventAttribution.map((e, i) => (
                <tr key={i}>
                  <td style={{ maxWidth: 240 }}>{e.event}{e.note && <div style={{ fontSize: 11, color: "var(--muted)" }}>{e.note}</div>}</td>
                  <td className="num">{e.att}</td>
                  <td className="num">{e.tours}</td>
                  <td className="num">{e.enrol}</td>
                  <td className="num">{e.rate}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="grid c3" style={{ marginBottom: 16 }}>
        <div className="card">
          <h3>Time to enrolment</h3>
          <div className="sub">Median days, lead → enrolled</div>
          <div style={{ marginTop: 16 }}>
            <TtRow lbl="Overall median" v={M.timeToEnrolment.medianDays} max={90} color="var(--purple)" />
            <TtRow lbl="Open House attendees" v={M.timeToEnrolment.openHouseMedian} max={90} color="var(--gold)" />
            <TtRow lbl="Direct leads" v={M.timeToEnrolment.directMedian} max={90} color="var(--blue)" />
            <TtRow lbl="75th percentile" v={M.timeToEnrolment.p75Days} max={90} color="var(--muted-2)" />
          </div>
        </div>

        <div className="card">
          <h3>Landing pages</h3>
          <div className="sub">A/B tests in progress</div>
          <table className="dt" style={{ marginTop: 10 }}>
            <thead><tr><th>Page</th><th className="num">Visits</th><th className="num">Rate</th></tr></thead>
            <tbody>
              {M.landingPages.map((p, i) => (
                <tr key={i}>
                  <td><div>{p.page}</div><div style={{ fontSize: 11, color: "var(--muted)" }}>{p.variant}</div></td>
                  <td className="num">{p.visits.toLocaleString()}</td>
                  <td className="num">{p.rate}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card">
          <h3>Audience segments</h3>
          <div className="sub">Where quality lives</div>
          <table className="dt" style={{ marginTop: 10 }}>
            <thead><tr><th>Segment</th><th className="num">Leads</th><th className="num">Qual</th><th className="num">Enrol</th></tr></thead>
            <tbody>
              {M.audienceSegments.map((s, i) => (
                <tr key={i}>
                  <td style={{ fontSize: 12 }}>{s.segment}</td>
                  <td className="num">{s.leads}</td>
                  <td className="num">{s.qualRate}%</td>
                  <td className="num">{s.enrolRate}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div className="sec-hd"><h3>Marketing narrative</h3><span className="sub">Federico Evangelista</span></div>
      <Narrative k="marketing" author="Federico Evangelista" role="Director of Communications and Experience" color="gold" data={narratives.marketing} onChange={(t)=>setNarratives(n=>({...n,marketing:{...n.marketing,text:t}}))} editable={editable} />
    </div>
  );
}

function TtRow({ lbl, v, max, color }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}>
        <span>{lbl}</span>
        <b style={{ fontVariantNumeric: "tabular-nums" }}>{v} days</b>
      </div>
      <div style={{ height: 7, background: "var(--ash-2)", borderRadius: 3, overflow: "hidden" }}>
        <div style={{ width: (v / max * 100) + "%", height: "100%", background: color, borderRadius: 3 }} />
      </div>
    </div>
  );
}

// ─── Board Snapshot ─────────────────────────
function SnapshotView({ narratives }) {
  const F = DATA.admissions.forecast;
  const R = DATA.retention;
  const M = DATA.marketing;
  return (
    <div className="view">
      <div className="view-hd">
        <div>
          <h2>Board Snapshot</h2>
          <p>Single-page monthly summary. Print to PDF for board packet.</p>
        </div>
        <button className="btn primary" onClick={() => window.print()}>Print to PDF</button>
      </div>
      <div className="snap">
        <div className="snap-hd">
          <div>
            <h2>ELC Enrolment Dashboard</h2>
            <div className="sub">Admissions, Retention, Marketing · April 2026 · {DATA.meta.academicYear}</div>
          </div>
          <div className="logo">ELC</div>
        </div>

        <div className="snap-sec">
          <h3>Enrolment forecast</h3>
          <p style={{ fontSize: 13, marginBottom: 10 }}><b>{F.confirmed} confirmed</b> for August 2026. Most-likely forecast <b>{F.scenarios.likely.total}</b> (range {F.scenarios.worst.total}–{F.scenarios.best.total}). <b>+{F.scenarios.likely.total - F.confirmed} new enrolments</b> needed to hit likely.</p>
          <ScenarioRange F={F} />
        </div>

        <div className="snap-sec">
          <h3>Retention health</h3>
          <p style={{ fontSize: 13, marginBottom: 10 }}><b>{R.totalAppliedOut} applied out</b> (vs 140 last yr). <b>{R.confirmedLeaving} confirmed leaving</b>: {R.forced} forced + {R.unforcedLeaving} unforced. NIST the dominant destination (23 accepted, mostly Kindergarten).</p>
          <LineChart
            labels={R.threeYearTrend.map(r => r.m)}
            series={[
              { data: R.threeYearTrend.map(r => r.y2324), color: "#D4D2CA", width: 1.5, dash: "4,3" },
              { data: R.threeYearTrend.map(r => r.y2425), color: "#a086be", width: 2 },
              { data: R.threeYearTrend.map(r => r.y2526), color: "#7d639b", width: 2.5 },
            ]}
            height={180}
          />
        </div>

        <div className="snap-sec">
          <h3>Marketing efficiency</h3>
          <p style={{ fontSize: 13, marginBottom: 10 }}><b>Cost per enrolment ฿{(M.costPerEnrolment.current/1000).toFixed(1)}k</b>, down from ฿51.4k in Aug. Referral converts 28% of leads → 41% of enrolments. Open House attendees close in 21 days vs 47 overall.</p>
          <LineChart
            labels={M.costPerEnrolment.trend.map(r => r.m)}
            series={[{ data: M.costPerEnrolment.trend.map(r => r.v), color: "#AC9D71", width: 2.5 }]}
            height={160}
            yFmt={(v) => "฿" + (v/1000).toFixed(0) + "k"}
          />
        </div>

        <div className="snap-sec">
          <h3>Department heads</h3>
          {["admissions","retention","marketing"].map(k => (
            <div key={k} style={{ marginBottom: 12 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: "var(--purple)", marginBottom: 4 }}>{narratives[k].author} · {narratives[k].role}</div>
              <p style={{ fontSize: 12, lineHeight: 1.55 }}>{narratives[k].text}</p>
            </div>
          ))}
        </div>

        <div className="snap-foot">
          <span>Generated {new Date().toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" })}</span>
          <span>Confidential · Leadership Team</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { PipelineView, RetentionView, MarketingView, SnapshotView });
