/* global React */
const { useState: useStateOv, useEffect: useEffectOv, useRef: useRefOv } = React;

function uid() {
  return "AB" + Math.random().toString(36).slice(2, 8).toUpperCase();
}

function labelFor(state, key) {
  const flow = window.BCO_BRANCHES[state.branch]?.flow || [];
  const q = flow.find(qq => qq.id === key) || (key === "altitude" ? window.BCO_BRANCHES[state.branch]?.altitude : null);
  if (!q) return null;
  const v = state.answers[key];
  if (q.kind === "multi") {
    if (!Array.isArray(v) || !v.length) return null;
    return v.map(id => q.options.find(o => o.id === id)?.label || id).join(" · ");
  }
  if (q.kind === "cards") {
    const opt = q.options.find(o => o.id === v);
    return opt?.label || null;
  }
  if (q.kind === "text") return v || null;
  if (q.kind === "compose") {
    if (!v) return null;
    return q.fields.map(f => v[f.id]).filter(Boolean).join(" · ");
  }
  return null;
}

function chipList(state, key) {
  const flow = window.BCO_BRANCHES[state.branch]?.flow || [];
  const q = flow.find(qq => qq.id === key);
  if (!q || q.kind !== "multi") return [];
  const v = state.answers[key] || [];
  return v.map(id => ({
    id,
    label: q.options.find(o => o.id === id)?.label || id,
  }));
}

function levers(state) {
  const { branch, answers } = state;
  const out = [];
  if (branch === "partnership" || branch === "combined") {
    const pi = answers.partnership_interest || [];
    const alt = answers.altitude;
    if (alt === "500p" || pi.includes("advocacy")) out.push({ arrow: "→", text: "Corporate Visionary Cultivation Lead", sub: "Highest tier" });
    else if (pi.includes("cause_marketing")) out.push({ arrow: "→", text: "Cause-Marketing Pitch Track", sub: "Mid-funnel" });
    else if (pi.includes("event_sponsorship")) out.push({ arrow: "→", text: "Sponsorship Inventory Outreach", sub: "FY26 packages" });
    else if (pi.length) out.push({ arrow: "→", text: "Partnership Discovery", sub: "20-min scoping call" });
    else out.push({ arrow: "→", text: "Awaiting partnership signal", sub: "" });
  }
  if (branch === "coverage") {
    const ed = answers.editorial_partnership;
    if (ed === "series" || ed === "data") out.push({ arrow: "→", text: "Editorial Partnership Pitch", sub: "Multi-quarter" });
    else if (ed && ed !== "noscope") out.push({ arrow: "→", text: "Press + Expert Source Match", sub: "" });
    else out.push({ arrow: "→", text: "Press Room Routing", sub: "Sources + data" });
  }
  if (branch === "personal") {
    const alt = answers.altitude;
    const action = answers.action || [];
    if (alt === "2500p" || action.includes("advocate")) out.push({ arrow: "→", text: "Major Gifts Outreach", sub: "" });
    else if (action.includes("tribute")) out.push({ arrow: "→", text: "Tribute Gift Flow", sub: "Pre-fill recommended" });
    else if (alt && alt !== "skip") out.push({ arrow: "→", text: "Standard Gift Flow", sub: "" });
    else out.push({ arrow: "→", text: "Newsletter + Resource Match", sub: "Low-touch" });
  }
  if (branch === "light") out.push({ arrow: "→", text: "Newsletter Drip · Low-Touch", sub: "" });
  return out;
}

function routes(state) {
  const { branch, answers } = state;
  const out = [];
  if (branch === "partnership" || branch === "combined") {
    out.push({ arrow: "→", text: "Daniela Gorenstein", sub: "VP Revenue Partnerships" });
    if (answers.altitude === "500p" || (answers.partnership_interest || []).includes("advocacy"))
      out.push({ arrow: "→", text: "Genvieve Shields", sub: "Director, Major Gifts" });
    else
      out.push({ arrow: "→", text: "Lauren Hughes", sub: "Director of Development" });
  }
  if (branch === "coverage") {
    out.push({ arrow: "→", text: "Anita Howell", sub: "Director of Communications" });
    out.push({ arrow: "→", text: "Dr. M. Klein", sub: "Medical Advisory Board liaison" });
  }
  if (branch === "personal") {
    if (state.answers.altitude === "2500p") out.push({ arrow: "→", text: "Genvieve Shields", sub: "Director, Major Gifts" });
    else out.push({ arrow: "→", text: "Community + Stewardship Team", sub: "" });
  }
  if (branch === "light") {
    out.push({ arrow: "→", text: "The Monthly newsletter list", sub: "Marketing ops" });
  }
  out.push({ arrow: "→", text: "CRM hand-off " + (state.email ? "queued" : "pending email confirmation"), sub: "Salesforce-NPC" });
  return out;
}

function progressPct(state, totalSteps) {
  const idx = state.stepIdx || 0;
  return Math.min(100, Math.round((idx / Math.max(1, totalSteps)) * 100));
}

function FlashLine({ children, deps }) {
  const ref = useRefOv(null);
  useEffectOv(() => {
    if (!ref.current) return;
    ref.current.classList.remove("ov-line-flash");
    void ref.current.offsetWidth;
    ref.current.classList.add("ov-line-flash");
  }, deps || []);
  return <div ref={ref}>{children}</div>;
}

function BuyerOverlay({ state, open, onClose, totalSteps }) {
  const overlay = window.BCO_DERIVE_OVERLAY(state);
  const sessId = state.sessionId;
  const phaseLabel = (() => {
    if (state.step === "hero") return "INTAKE PENDING";
    if (state.step === "celebration") return "RECORD SEALED";
    if (state.step === "email") return "IDENTITY CAPTURE";
    return "FLOW ACTIVE";
  })();

  const motiv = window.BCO_MOTIVATION.find(m => m.id === state.motivation);
  const branchInfo = window.BCO_BRANCHES[state.branch];
  const role = labelFor(state, "role") || (state.answers.role_company?.role_text);
  const company = labelFor(state, "company") || (state.answers.role_company?.company);
  const publication = labelFor(state, "publication");
  const altitude = labelFor(state, "altitude");
  const stage = labelFor(state, "stage");
  const partnershipChips = chipList(state, "partnership_interest");
  const coverageChips = chipList(state, "coverage_interest");
  const actionChips = chipList(state, "action");
  const decisionAuthority = (() => {
    if (state.branch !== "partnership" && state.branch !== "combined") return null;
    switch (state.answers.role) {
      case "cmo": return "Owns the decision";
      case "svp": return "Owns or co-owns";
      case "dir": return "Strong influence";
      case "founder": return "Owns everything";
      case "ic": return "Influences upward";
      case "other": return "TBD on follow-up";
      default: return null;
    }
  })();

  const ls = levers(state);
  const rs = routes(state);

  return (
    <aside className={`overlay-pane ${open ? "open" : ""}`}>
      <div className="ov-head">
        <div className="ov-head-l">
          <span className="ov-pulse" />
          <span className="ov-title">PARTNERSHIPS RECORD · breastcancer.org</span>
        </div>
        <span className="ov-id">▸ live</span>
      </div>

      <div className="ov-sess">
        tenant.breastcancerorg · sess.<span>{sessId}</span>
      </div>

      <div className="ov-section">
        <div className="ov-section-label"><span className="ix">01</span> SESSION</div>
        <FlashLine deps={[state.step, state.motivation]}>
          <dl className="ov-kv">
            <dt>Phase</dt><dd>{phaseLabel}</dd>
            <dt>Motivation</dt><dd>{motiv ? motiv.label.replace(/\.$/, "") : <span className="ov-empty">awaiting Q01</span>}</dd>
            <dt>Branch</dt><dd>{branchInfo ? branchInfo.label.toUpperCase() : <span className="ov-empty">—</span>}</dd>
            <dt>Progress</dt>
            <dd>
              <div className="ov-prog">
                <div className="ov-prog-bar"><div className="ov-prog-fill" style={{ width: `${progressPct(state, totalSteps)}%` }} /></div>
                <span>{progressPct(state, totalSteps)}%</span>
              </div>
            </dd>
          </dl>
        </FlashLine>
      </div>

      <div className="ov-section">
        <div className="ov-section-label"><span className="ix">02</span> AUDIENCE TAGS</div>
        <FlashLine deps={[overlay.tags.join(",")]}>
          {overlay.tags.length === 0
            ? <span className="ov-empty">tags populate as signals arrive</span>
            : <div className="ov-tags">
                {overlay.tags.map(t => <span key={t} className="ov-tag">{t}</span>)}
              </div>
          }
        </FlashLine>
      </div>

      <div className="ov-section">
        <div className="ov-section-label"><span className="ix">03</span> ATTENDEE PROFILE</div>
        <FlashLine deps={[role, company, publication, stage, state.email]}>
          <dl className="ov-kv">
            <dt>Name</dt><dd>{state.name || <span className="ov-empty">—</span>}</dd>
            <dt>Email</dt><dd>{state.email || <span className="ov-empty">awaiting Q08</span>}</dd>
            {(state.branch === "partnership" || state.branch === "combined" || state.branch === "light") && <>
              <dt>Role</dt><dd>{role || <span className="ov-empty">—</span>}</dd>
              <dt>Company</dt><dd>{company || <span className="ov-empty">—</span>}</dd>
              <dt>Decision auth.</dt><dd>{decisionAuthority || <span className="ov-empty">—</span>}</dd>
            </>}
            {state.branch === "coverage" && <>
              <dt>Role</dt><dd>{role || <span className="ov-empty">—</span>}</dd>
              <dt>Publication</dt><dd>{publication || <span className="ov-empty">—</span>}</dd>
            </>}
            {state.branch === "personal" && <>
              <dt>Journey stage</dt><dd>{stage || <span className="ov-empty">—</span>}</dd>
              <dt>Resonance</dt><dd>{labelFor(state, "support") || <span className="ov-empty">—</span>}</dd>
            </>}
            {state.branch === "combined" && <>
              <dt>Journey stage</dt><dd>{stage || <span className="ov-empty">—</span>}</dd>
            </>}
          </dl>
        </FlashLine>
      </div>

      {(state.branch === "partnership" || state.branch === "combined") && (
        <div className="ov-section">
          <div className="ov-section-label"><span className="ix">04</span> PARTNERSHIP INTEREST</div>
          <FlashLine deps={[partnershipChips.length]}>
            {partnershipChips.length
              ? <div className="ov-chips">{partnershipChips.map(c => <span key={c.id} className="ov-chip">[{c.id}]</span>)}</div>
              : <span className="ov-empty">awaiting Q05</span>}
          </FlashLine>
          {altitude && <dl className="ov-kv" style={{ marginTop: 10 }}>
            <dt>Altitude</dt><dd>{altitude}</dd>
          </dl>}
        </div>
      )}

      {state.branch === "coverage" && (
        <div className="ov-section">
          <div className="ov-section-label"><span className="ix">04</span> COVERAGE INTEREST</div>
          <FlashLine deps={[coverageChips.length]}>
            {coverageChips.length
              ? <div className="ov-chips">{coverageChips.map(c => <span key={c.id} className="ov-chip">[{c.id}]</span>)}</div>
              : <span className="ov-empty">awaiting Q05</span>}
          </FlashLine>
          {labelFor(state, "editorial_partnership") && <dl className="ov-kv" style={{ marginTop: 10 }}>
            <dt>Ed. scope</dt><dd>{labelFor(state, "editorial_partnership")}</dd>
          </dl>}
        </div>
      )}

      {state.branch === "personal" && (
        <div className="ov-section">
          <div className="ov-section-label"><span className="ix">04</span> PERSONAL ACTION</div>
          <FlashLine deps={[actionChips.length]}>
            {actionChips.length
              ? <div className="ov-chips">{actionChips.map(c => <span key={c.id} className="ov-chip">[{c.id}]</span>)}</div>
              : <span className="ov-empty">awaiting Q05</span>}
          </FlashLine>
          {altitude && <dl className="ov-kv" style={{ marginTop: 10 }}>
            <dt>Giving range</dt><dd>{altitude}</dd>
          </dl>}
        </div>
      )}

      <div className="ov-section">
        <div className="ov-section-label"><span className="ix">05</span> PRIMARY LEVER</div>
        <FlashLine deps={[ls.map(l => l.text).join("|")]}>
          {ls.length === 0
            ? <span className="ov-empty">awaiting signals</span>
            : ls.map((l, i) => (
              <div key={i} className="ov-route">
                <span className="arrow">{l.arrow}</span>
                <span>{l.text}</span>
                {l.sub && <span className="sub">{l.sub}</span>}
              </div>
            ))
          }
        </FlashLine>
      </div>

      <div className="ov-section">
        <div className="ov-section-label"><span className="ix">06</span> ROUTING</div>
        <FlashLine deps={[rs.map(r => r.text).join("|")]}>
          {rs.length === 0
            ? <span className="ov-empty">awaiting branch</span>
            : rs.map((r, i) => (
              <div key={i} className="ov-route">
                <span className="arrow">{r.arrow}</span>
                <span>{r.text}</span>
                {r.sub && <span className="sub">{r.sub}</span>}
              </div>
            ))
          }
        </FlashLine>
      </div>

      <div className="ov-section ov-config">
        <div className="ov-section-label"><span className="ix">CFG</span> PROGRAM CONFIGURATION</div>
        <div className="ov-config-row"><span>Engine</span><span>Journey Engine · v4.2</span></div>
        <div className="ov-config-row"><span>Tenant</span><span>#5 · bco</span></div>
        <div className="ov-config-row"><span>Sibling tenants</span><span>Marriott · Chase · Southwest · BTC</span></div>
        <div className="ov-config-row"><span>Demo mode</span><span className="on">● ON</span></div>
        <div className="ov-config-row"><span>Live data</span><span className="off">○ OFF</span></div>
        <div className="ov-config-row"><span>Third-party share</span><span className="off">○ DISABLED</span></div>
      </div>

      {open && (
        <button
          onClick={onClose}
          style={{
            position: "sticky", bottom: 16, marginLeft: "auto", marginRight: 16,
            display: "block",
            background: "rgba(255,255,255,0.08)", color: "var(--overlay-ink)",
            border: "1px solid var(--overlay-line)", borderRadius: 999,
            padding: "8px 14px", font: "inherit", fontSize: 12.5, cursor: "pointer"
          }}
        >Close ✕</button>
      )}
    </aside>
  );
}

Object.assign(window, { BuyerOverlay, uid });
