/* Portco door: My Company, Assessment (QRAP), Playbooks (read). */

/* ---- Build the full question taxonomy once ---- */
const ELEMENT_SUFFIX = [
  { k: "Strategy and ownership", q: sp => `Is there clear ownership and a defined strategy for ${sp.toLowerCase()}?` },
  { k: "Process and documentation", q: sp => `Are ${sp.toLowerCase()} processes documented and standardized across the organization?` },
  { k: "Tools and systems", q: sp => `Are the right tools and systems in place to support ${sp.toLowerCase()}?` },
  { k: "Measurement and KPIs", q: sp => `Is ${sp.toLowerCase()} measured with clear KPIs and reviewed each quarter?` },
  { k: "Continuous improvement", q: sp => `Is ${sp.toLowerCase()} continuously reviewed and improved against benchmarks?` },
];
const QUESTIONS = VCP.PILLARS.map(p => ({
  pillar: p.key,
  subpillars: p.subpillars.map(sp => ({
    name: sp,
    elements: ELEMENT_SUFFIX.map((suf, i) => {
      const worked = p.key === "Operational" && sp === "Process Optimization" && i === 0;
      return {
        id: `${p.key}|${sp}|${i}`,
        element: worked ? VCP.workedQuestion.element : suf.k,
        question: worked ? VCP.workedQuestion.question : suf.q(sp),
        descriptors: worked ? VCP.workedQuestion.descriptors : VCP.genericDescriptors,
      };
    }),
  })),
}));
const TOTAL_Q = QUESTIONS.reduce((a, p) => a + p.subpillars.length * 5, 0);

function seedAnswers() {
  const helios = VCP.companyById("helios");
  const ans = {};
  let h = 7;
  QUESTIONS.forEach(p => {
    const base = helios.pillars[p.pillar][0];
    p.subpillars.forEach(sp => {
      sp.elements.forEach(el => {
        // leave one subpillar unanswered so badges + Find Next + Submit are demonstrable
        if (p.pillar === "Buy and Build" && sp.name === "Add-On Acquisitions") return;
        h = (h * 1103515245 + 12345) & 0x7fffffff;
        const jitter = ((h % 10) / 10 - 0.45);
        let s = Math.round(Math.max(1, Math.min(5, base + jitter)));
        ans[el.id] = { score: s };
      });
    });
  });
  return ans;
}

function Assessment({ state, go }) {
  const co = VCP.companyById(state.companyId || "helios");
  const isFirm = state.door === "firm";
  const [answers, setAnswers] = useState(seedAnswers);
  const [submitted, setSubmitted] = useState(false);
  const [view, setView] = useState("current"); // current | history
  const dl = state.deeplink || {};
  const [pillar, setPillar] = useState(dl.pillar || "Operational");
  const [sub, setSub] = useState(null);
  const [saveState, flash] = useSaveFlash();
  const [highlight, setHighlight] = useState(dl.subpillar ? null : null);

  const pillarDef = QUESTIONS.find(p => p.pillar === pillar);
  const subDef = pillarDef.subpillars.find(s => s.name === (sub || (dl.pillar === pillar && dl.subpillar) || pillarDef.subpillars[0].name)) || pillarDef.subpillars[0];

  const isAnswered = id => answers[id] && (answers[id].score != null || answers[id].na);
  const answeredCount = Object.keys(answers).filter(isAnswered).length;
  const pct = Math.round((answeredCount / TOTAL_Q) * 100);

  const unansweredInPillar = p => QUESTIONS.find(x => x.pillar === p).subpillars.reduce((a, s) => a + s.elements.filter(e => !isAnswered(e.id)).length, 0);
  const unansweredInSub = (p, sName) => QUESTIONS.find(x => x.pillar === p).subpillars.find(s => s.name === sName).elements.filter(e => !isAnswered(e.id)).length;

  const setAnswer = (id, patch) => { if (submitted || isFirm) return; setAnswers(a => ({ ...a, [id]: { ...a[id], ...patch } })); flash(); };
  const selectLevel = (id, lvl) => { const cur = answers[id]; if (cur && cur.score === lvl && !cur.na) setAnswer(id, { score: null }); else setAnswer(id, { score: lvl, na: false }); };
  const setNA = id => { const cur = answers[id]; if (cur && cur.na) setAnswer(id, { na: false, score: null }); else setAnswer(id, { na: true, score: null }); };

  const findNext = () => {
    for (const p of QUESTIONS) for (const s of p.subpillars) for (const e of s.elements) if (!isAnswered(e.id)) { setPillar(p.pillar); setSub(s.name); setHighlight(e.id); return; }
    window.vcpToast?.("Everything is answered");
  };
  const submit = () => { setSubmitted(true); window.vcpToast?.("Assessment submitted · scores rolling up to the firm"); };

  if (view === "history") return <AssessmentHistory co={co} onOpen={() => setView("current")} onBack={() => setView("history")} go={go} state={state} setView={setView} />;

  return <div className="route-fade" style={{ padding: "22px 28px 96px", maxWidth: 1100, margin: "0 auto" }}>
    <SectionHeader eyebrow={(isFirm ? "Firm read · " : "Module C · ") + co.name} title={"Quarterly assessment · " + state.period}
      sub={isFirm ? "You are inspecting the company's own QRAP. The scores here roll up to the maturity heatmap." : "Self-assess against the eight-pillar model. Each answer saves as you go and rolls up to your maturity scores."}
      right={<><Btn variant="ghost" size="sm" icon="clock" onClick={() => setView("history")}>History</Btn><SaveIndicator state={saveState} /></>} />

    {(submitted || isFirm) && <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 14px", background: isFirm ? "var(--accent-soft)" : "var(--positive-soft)", borderRadius: 10, marginBottom: 16, fontSize: 13, color: isFirm ? "var(--accent)" : "var(--positive)", fontWeight: 600 }}>
      <Icon name={isFirm ? "shield" : "check"} size={16} />{isFirm ? "Read-only · firm inspecting the company's submitted answers." : "Submitted · this questionnaire is now read-only."}
    </div>}

    {/* pillar tabs */}
    <div style={{ display: "flex", gap: 4, overflowX: "auto", paddingBottom: 4, marginBottom: 12, borderBottom: "1px solid var(--line)" }}>
      {QUESTIONS.map(p => { const u = unansweredInPillar(p.pillar); const on = pillar === p.pillar; return <button key={p.pillar} onClick={() => { setPillar(p.pillar); setSub(p.subpillars[0].name); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "8px 12px", border: "none", borderBottom: "2px solid " + (on ? "var(--accent)" : "transparent"), background: "transparent", color: on ? "var(--ink)" : "var(--ink-soft)", fontWeight: on ? 600 : 500, fontSize: 13, whiteSpace: "nowrap", marginBottom: -1 }}>
        {p.pillar}{u > 0 && <span style={{ fontSize: 10, fontWeight: 700, background: "var(--warn-soft)", color: "var(--warn)", borderRadius: 100, padding: "1px 6px" }}>{u}</span>}
      </button>; })}
    </div>

    {/* subpillar pills */}
    <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 18 }}>
      {pillarDef.subpillars.map(s => { const u = unansweredInSub(pillar, s.name); const on = subDef.name === s.name; return <button key={s.name} onClick={() => { setSub(s.name); setHighlight(null); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 11px", borderRadius: 100, border: "1px solid " + (on ? "var(--accent)" : "var(--line)"), background: on ? "var(--accent-soft)" : "var(--surface-card)", color: on ? "var(--accent)" : "var(--ink-muted)", fontSize: 12, fontWeight: 600 }}>
        {s.name}{u > 0 && <span style={{ fontSize: 10, fontWeight: 700, background: "var(--warn-soft)", color: "var(--warn)", borderRadius: 100, padding: "0 5px" }}>{u}</span>}
      </button>; })}
    </div>

    {/* question cards */}
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {subDef.elements.map((el, idx) => <QuestionCard key={el.id} el={el} num={idx + 1} ans={answers[el.id]} highlight={highlight === el.id} readOnly={submitted || isFirm}
        onSelect={lvl => selectLevel(el.id, lvl)} onNA={() => setNA(el.id)} onComment={txt => setAnswer(el.id, { comment: txt })} />)}
    </div>

    {/* fixed progress bar */}
    <div style={{ position: "fixed", bottom: 0, left: "var(--sidebar-w)", right: 0, background: "var(--surface-card)", borderTop: "1px solid var(--line)", padding: "12px 28px", display: "flex", alignItems: "center", gap: 18, zIndex: 40 }}>
      <div style={{ flex: 1, maxWidth: 420 }}>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, marginBottom: 5 }}><span className="micro">Progress</span><span className="tabular" style={{ fontWeight: 700 }}>{answeredCount}/{TOTAL_Q} · {pct}%</span></div>
        <div style={{ height: 7, background: "var(--surface-deep)", borderRadius: 100, overflow: "hidden" }}><div style={{ width: pct + "%", height: "100%", background: pct === 100 ? "var(--positive)" : "var(--accent)", transition: "width 200ms ease" }} /></div>
      </div>
      <div style={{ flex: 1 }} />
      {!isFirm && !submitted && <Btn variant="ghost" icon="arrowDown" onClick={findNext}>Find next unanswered</Btn>}
      {!isFirm && <Btn icon="check" disabled={answeredCount < TOTAL_Q || submitted} onClick={submit}>{submitted ? "Submitted" : "Submit assessment"}</Btn>}
      {isFirm && <Btn variant="ghost" icon="arrowLeft" onClick={() => go({ door: "firm", route: "co-valuecreation", companyId: co.id, deeplink: null })}>Back to firm view</Btn>}
    </div>
  </div>;
}

function QuestionCard({ el, num, ans, highlight, readOnly, onSelect, onNA, onComment }) {
  const [comment, setComment] = useState(ans && ans.comment || "");
  const levels = [1, 2, 3, 4, 5];
  const selected = ans && ans.score;
  const na = ans && ans.na;
  return <div style={{ background: "var(--surface-card)", border: "1px solid " + (highlight ? "var(--accent)" : "var(--line)"), borderRadius: "var(--radius)", padding: 18, boxShadow: highlight ? "0 0 0 3px var(--accent-soft)" : "var(--shadow-card)", transition: "all 150ms ease" }}>
    <div style={{ display: "flex", gap: 10, marginBottom: 14 }}>
      <span style={{ fontSize: 11, fontWeight: 700, color: "var(--ink-faint)", marginTop: 2 }} className="tabular">{String(num).padStart(2, "0")}</span>
      <div style={{ flex: 1 }}>
        <div className="micro" style={{ marginBottom: 4 }}>{el.element}</div>
        <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.4 }}>{el.question}</div>
      </div>
      {(selected != null || na) && <Icon name="check" size={16} color="var(--positive)" />}
    </div>
    <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
      {levels.map(lvl => { const on = selected === lvl; return <button key={lvl} disabled={readOnly} onClick={() => onSelect(lvl)} style={{
        display: "flex", gap: 11, alignItems: "flex-start", textAlign: "left", padding: "10px 12px", borderRadius: 9,
        border: "1px solid " + (on ? "var(--accent)" : "var(--line)"), background: on ? "var(--accent-soft)" : "var(--surface-card)",
        cursor: readOnly ? "default" : "pointer", transition: "all 120ms ease", opacity: readOnly && !on ? 0.6 : 1,
      }}>
        <span style={{ width: 18, height: 18, borderRadius: "50%", border: "2px solid " + (on ? "var(--accent)" : "var(--line)"), background: on ? "var(--accent)" : "transparent", flexShrink: 0, marginTop: 1, display: "inline-flex", alignItems: "center", justifyContent: "center" }}>{on && <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#fff" }} />}</span>
        <div>
          <span style={{ fontSize: 12.5, fontWeight: 700, color: on ? "var(--accent)" : "var(--ink)" }}>{VCP.levelLabels[lvl - 1]}</span>
          <div style={{ fontSize: 12, color: "var(--ink-muted)", marginTop: 2, lineHeight: 1.45 }}>{el.descriptors[lvl]}</div>
        </div>
      </button>; })}
      <button disabled={readOnly} onClick={onNA} style={{ display: "flex", gap: 11, alignItems: "center", padding: "9px 12px", borderRadius: 9, border: "1px dashed " + (na ? "var(--ink-muted)" : "var(--line)"), background: na ? "var(--surface-deep)" : "transparent", cursor: readOnly ? "default" : "pointer" }}>
        <span style={{ width: 18, height: 18, borderRadius: "50%", border: "2px solid " + (na ? "var(--ink-muted)" : "var(--line)"), background: na ? "var(--ink-muted)" : "transparent", flexShrink: 0 }} />
        <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--ink-muted)" }}>(N/A) Not Applicable</span>
        <span style={{ fontSize: 11, color: "var(--ink-faint)", marginLeft: 4 }}>excluded from averages</span>
      </button>
    </div>
    {(selected != null || na) && !readOnly && <input value={comment} onChange={e => setComment(e.target.value)} onBlur={() => onComment(comment)} placeholder="Add a comment (optional)" style={{ marginTop: 10, width: "100%", border: "1px solid var(--line)", borderRadius: 8, padding: "8px 10px", background: "var(--surface)", outline: "none", fontSize: 12.5 }} />}
    {readOnly && comment && <div style={{ marginTop: 10, padding: "8px 10px", background: "var(--surface)", borderRadius: 8, fontSize: 12.5, color: "var(--ink-muted)" }}><b>Comment: </b>{comment}</div>}
  </div>;
}

function AssessmentHistory({ co, setView, state }) {
  const rows = [{ q: "25Q2", status: "Open", state: 0 }, { q: "25Q1", status: "Submitted", state: 1 }, { q: "24Q4", status: "Submitted", state: 1 }, { q: "24Q3", status: "Submitted", state: 1 }];
  return <div className="route-fade" style={{ padding: "22px 28px 60px", maxWidth: 900, margin: "0 auto" }}>
    <SectionHeader eyebrow={"Module C · " + co.name} title="Assessment history"
      right={<Btn size="sm" icon="arrowLeft" variant="ghost" onClick={() => setView("current")}>Current questionnaire</Btn>} />
    <div style={{ background: "var(--surface-card)", border: "1px solid var(--line)", borderRadius: "var(--radius)", overflow: "hidden", boxShadow: "var(--shadow-card)" }}>
      {rows.map((r, i) => <div key={r.q} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 18px", borderBottom: i < rows.length - 1 ? "1px solid var(--line-soft)" : "none" }}>
        <span style={{ width: 38, height: 38, borderRadius: 9, background: "var(--surface-deep)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="list" size={17} color="var(--ink-soft)" /></span>
        <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14 }} className="tabular">Quarterly assessment {r.q}</div><div style={{ fontSize: 12, color: "var(--ink-soft)" }}>{co.name}</div></div>
        <Badge variant={r.state === 0 ? "warn" : "positive"}>{r.status}</Badge>
        <Btn size="sm" variant={r.state === 0 ? "primary" : "ghost"} icon={r.state === 0 ? "pencil" : "fileText"} onClick={() => setView("current")}>{r.state === 0 ? "Continue" : "View"}</Btn>
      </div>)}
    </div>
  </div>;
}

/* ---- Portco home: My Company ---- */
function PortcoHome({ state, go }) {
  const c = VCP.companyById(state.companyId || "helios");
  const fin = VCP.heliosFinancials;
  const tasks = VCP.allTasks.filter(t => t.company === c.id);
  return <div className="route-fade" style={{ padding: "22px 28px 60px", maxWidth: 1240, margin: "0 auto" }}>
    <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 8 }}>
      <CompanyMark company={c} size={48} />
      <div><div style={{ display: "flex", alignItems: "center", gap: 10 }}><h2 style={{ margin: 0, fontSize: 22, fontWeight: 800, letterSpacing: "-0.02em" }}>{c.name}</h2><Badge variant="positive">{c.status}</Badge></div>
        <div style={{ fontSize: 12.5, color: "var(--ink-muted)", marginTop: 4 }}>{c.sector} · {c.fundLabel} · in the Northbridge Value Creation Platform</div></div>
    </div>
    <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "10px 14px", background: "var(--accent-soft)", borderRadius: 10, fontSize: 12.5, color: "var(--accent)", marginBottom: 22 }}>
      <Icon name="shield" size={15} /> You are in your own company's view. Your numbers are read-only; your assessment and plan are yours to update.
    </div>

    <div className="micro" style={{ marginBottom: 8 }}>At a glance · {state.period}</div>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 22 }}>
      <GlanceCard label="Enterprise value" value={VCP.fmtM(c.ev).replace("EUR ", "€")} mod="A" />
      <GlanceCard label="Equity value" value={VCP.fmtM(c.equity).replace("EUR ", "€")} mod="A" />
      <GlanceCard label="Maturity" value={<span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><ScoreBadge score={c.maturity} /><TrendTag trend={VCP.trendOf(c.overallSeries)} /></span>} mod="C" />
      <GlanceCard label="Open tasks" value={c.open} mod="B" />
    </div>

    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
      <Card pad={18}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}><div className="micro">Your value-creation plan</div><Btn size="sm" variant="ghost" icon="externalLink" onClick={() => go({ route: "pc-assessment" })}>Assessment</Btn></div>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {VCP.PILLAR_KEYS.slice(0, 5).map(p => <div key={p} style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontSize: 12.5, width: 120 }}>{p}</span>
            <div style={{ flex: 1, height: 7, background: "var(--surface-deep)", borderRadius: 100, overflow: "hidden" }}><div style={{ width: (c.pillars[p][0] / 5 * 100) + "%", height: "100%", background: BAND_FG[VCP.scoreBand(c.pillars[p][0])] }} /></div>
            <ScoreBadge score={c.pillars[p][0]} size="sm" />
          </div>)}
        </div>
      </Card>
      <Card pad={18}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}><div className="micro">Open work assigned to your team</div></div>
        {tasks.slice(0, 5).map(t => <div key={t.id} style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px 0", borderBottom: "1px solid var(--line-soft)" }}>
          <Badge variant={PRIORITY_VARIANT[t.priority]} style={{ minWidth: 8 }}>{t.priority[0].toUpperCase()}</Badge>
          <span style={{ fontSize: 12.5, flex: 1 }}>{t.name}</span>
          <span className="tabular" style={{ fontSize: 11, color: t.overdue ? "var(--danger)" : "var(--ink-soft)" }}>{t.due}</span>
        </div>)}
      </Card>
    </div>

    <Card style={{ marginTop: 18 }} pad={18}>
      <div className="micro" style={{ marginBottom: 12 }}>Documents shared with you</div>
      <DocList docs={VCP.companyDocs} readOnly />
    </Card>
  </div>;
}

function PlaybooksRead({ state, go }) {
  return <div className="route-fade" style={{ padding: "22px 28px 60px", maxWidth: 1100, margin: "0 auto" }}>
    <SectionHeader eyebrow="Module C · Playbooks" title="Playbooks for your company"
      sub="The reusable plays relevant to your improvement areas, read-only." />
    <PlaybookLibrary readOnly go={go} />
  </div>;
}

Object.assign(window, { Assessment, PortcoHome, PlaybooksRead, QuestionCard, AssessmentHistory, QUESTIONS, TOTAL_Q });
