/* Firm company workspace: Value Creation matrix + Collaboration (Work + Documents + People). */

/* ---- matrix generator (same shape as heatmap, company scope) ---- */
function companyMatrix(c) {
  if (c.id === "helios") return { matrix: VCP.heliosMatrix, order: ["Average", ...VCP.PILLAR_KEYS] };
  const last = c.overallSeries[c.overallSeries.length - 1];
  const m = { Average: c.overallSeries };
  VCP.PILLAR_KEYS.forEach(p => {
    const latest = c.pillars[p][0];
    m[p] = c.overallSeries.map(ov => +Math.max(1, Math.min(5, latest * (ov / last))).toFixed(1));
  });
  return { matrix: m, order: ["Average", ...VCP.PILLAR_KEYS] };
}
function subpillarMatrix(c, pillar) {
  const def = VCP.PILLARS.find(p => p.key === pillar);
  const base = c.pillars[pillar][0];
  const isHeliosTech = c.id === "helios" && pillar === "Technology";
  const last = c.overallSeries[c.overallSeries.length - 1];
  return def.subpillars.map((sp, i) => {
    const latest = isHeliosTech ? VCP.heliosTechSubpillars[sp] : Math.max(1, Math.min(5, +(base + ((i % 3) - 1) * 0.3).toFixed(1)));
    const series = c.overallSeries.map(ov => +Math.max(1, Math.min(5, latest * (ov / last))).toFixed(1));
    return { sp, series };
  });
}

function CompanyValueCreation({ state, go }) {
  const c = VCP.companyById(state.companyId);
  const { matrix, order } = companyMatrix(c);
  const [expanded, setExpanded] = useState({});
  const Qs = VCP.QUARTERS.concat(["25Q3"]); // 25Q3 not yet assessed -> dash

  const matRow = (label, series, opts = {}) => {
    const trend = VCP.trendOf(series);
    return <tr key={label} style={{ background: opts.avg ? "var(--accent-soft)" : (opts.sub ? "var(--surface)" : "transparent") }}>
      <td style={{ padding: opts.sub ? "7px 12px 7px 38px" : "9px 14px", borderBottom: "1px solid var(--line-soft)", position: "sticky", left: 0, background: opts.avg ? "var(--accent-soft)" : (opts.sub ? "var(--surface)" : "var(--surface-card)"), fontWeight: opts.avg ? 700 : opts.sub ? 400 : 600, fontSize: opts.sub ? 12.5 : 13, color: opts.avg ? "var(--accent)" : "var(--ink)" }}>
        {opts.expandable ? <button onClick={opts.onToggle} style={{ display: "inline-flex", alignItems: "center", gap: 7, border: "none", background: "none", font: "inherit", fontWeight: 600, cursor: "pointer", color: "var(--ink)", padding: 0 }}><Icon name={opts.open ? "chevronD" : "chevronR"} size={13} color="var(--ink-soft)" />{label}</button> : label}
      </td>
      {Qs.map((q, i) => { const v = series[i]; return <td key={q} style={{ textAlign: "center", padding: "5px 6px", borderBottom: "1px solid var(--line-soft)" }}>{v == null ? <span style={{ color: "var(--ink-faint)" }}>—</span> : <ScoreBadge score={v} size="sm" />}</td>; })}
      <td style={{ textAlign: "center", borderBottom: "1px solid var(--line-soft)" }}><TrendTag trend={trend} /></td>
    </tr>;
  };

  return <div className="route-fade" style={{ padding: "22px 28px 60px", maxWidth: 1240, margin: "0 auto" }}>
    <SectionHeader eyebrow="Module C · Value Creation" title="Maturity over time"
      sub="Eight pillars by quarter. Expand any pillar to its subpillars, or open the assessment to inspect the answers."
      right={<Btn variant="ghost" size="sm" icon="externalLink" onClick={() => go({ door: "portco", route: "pc-assessment", companyId: c.id })}>Open assessment</Btn>} />

    <div style={{ display: "flex", gap: 12, marginBottom: 16 }}>
      <div style={{ flex: 1 }}><KPIStrip items={[
        { label: "Overall maturity", value: c.maturity.toFixed(1), color: BAND_FG[VCP.scoreBand(c.maturity)] },
        { label: "Trend (4 quarters)", value: <TrendTag trend={VCP.trendOf(c.overallSeries)} delta={+(c.overallSeries[3] - c.overallSeries[0]).toFixed(1)} showLabel /> },
        { label: "Strongest pillar", value: VCP.PILLAR_KEYS.reduce((a, b) => c.pillars[b][0] > c.pillars[a][0] ? b : a).replace("Technology", "Tech"), color: "var(--positive)" },
        { label: "Quarters assessed", value: "4" },
      ]} /></div>
    </div>

    <div style={{ background: "var(--surface-card)", border: "1px solid var(--line)", borderRadius: "var(--radius)", overflow: "hidden", boxShadow: "var(--shadow-card)" }}>
      <div style={{ overflowX: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, minWidth: 720, tableLayout: "fixed" }}>
          <colgroup>
            <col />
            {Qs.map(q => <col key={q} style={{ width: 84 }} />)}
            <col style={{ width: 84 }} />
          </colgroup>
          <thead><tr style={{ background: "var(--surface-deep)" }}>
            <th style={{ textAlign: "left", padding: "10px 14px", fontSize: 11, textTransform: "uppercase", letterSpacing: "0.04em", color: "var(--ink-soft)", fontWeight: 600, position: "sticky", left: 0, background: "var(--surface-deep)" }}>Pillar</th>
            {Qs.map(q => <th key={q} className="tabular" style={{ textAlign: "center", padding: "10px 6px", fontSize: 11, fontWeight: 600, color: "var(--ink-soft)" }}>{q}</th>)}
            <th style={{ textAlign: "center", padding: "10px 8px", fontSize: 11, textTransform: "uppercase", color: "var(--ink-soft)", fontWeight: 600 }}>Trend</th>
          </tr></thead>
          <tbody>
            {order.map(key => {
              if (key === "Average") return matRow("Average", matrix.Average.concat([null]), { avg: true });
              const open = expanded[key];
              const rows = [matRow(key, matrix[key].concat([null]), { expandable: true, open, onToggle: () => setExpanded(e => ({ ...e, [key]: !e[key] })) })];
              if (open) subpillarMatrix(c, key).forEach(({ sp, series }) => rows.push(matRow(sp, series.concat([null]), { sub: true })));
              return rows;
            })}
          </tbody>
        </table>
      </div>
    </div>
    <div style={{ marginTop: 10, fontSize: 11.5, color: "var(--ink-faint)", display: "flex", gap: 16 }}>
      <span>25Q3 not yet assessed</span>
      <span style={{ display: "inline-flex", gap: 10 }}>
        {[["≥4.0", "green"], ["≥3.0", "teal"], ["≥2.0", "yellow"], ["<2.0", "red"]].map(([l, b]) => <span key={l} style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: BAND_BG[b], border: "1px solid " + BAND_FG[b] }} />{l}</span>)}
      </span>
    </div>
  </div>;
}

/* ---- Collaboration: Work + Documents + People ---- */
function CompanyCollaboration({ state, go }) {
  const c = VCP.companyById(state.companyId);
  const [tab, setTab] = useState(state.deeplink && state.deeplink.tab || "work");
  useEffect(() => { if (state.deeplink && state.deeplink.tab) go({ deeplink: null }); }, []);
  return <div className="route-fade" style={{ padding: "22px 28px 60px", maxWidth: 1240, margin: "0 auto" }}>
    <SectionHeader eyebrow="Module B · Collaboration" title="Running the work"
      sub="This company's projects and tasks, its documents, and its people." />
    <Tabs tabs={[{ key: "work", label: "Work", icon: "columns" }, { key: "docs", label: "Documents", icon: "folder" }, { key: "people", label: "People", icon: "users" }]} active={tab} onChange={setTab} />
    {tab === "work" && <CompanyWork c={c} key={"w" + c.id} />}
    {tab === "docs" && <CompanyDocs c={c} key={"d" + c.id} />}
    {tab === "people" && <CompanyPeople c={c} key={"p" + c.id} />}
  </div>;
}

function CompanyWork({ c }) {
  const initProjects = c.id === "helios" ? VCP.heliosProjects : [{ id: "px", name: c.sector + " value plan", theme: "Operational", company: c.id, start: c.entryDate, due: "2025-12-31", taskIds: VCP.allTasks.filter(t => t.company === c.id).map(t => t.id) }];
  const [projects, setProjects] = useState(initProjects);
  const [addP, setAddP] = useState(false);
  const tasksOf = (ids) => VCP.allTasks.filter(t => ids.includes(t.id));
  const [open, setOpen] = useState({ [projects[0].id]: true });
  const addProject = (p) => { setProjects(ps => [...ps, p]); setOpen(o => ({ ...o, [p.id]: true })); };
  return <div>
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
      <div className="micro">Projects</div><Btn size="sm" icon="plus" onClick={() => setAddP(true)}>Add project</Btn>
    </div>
    <div style={{ display: "flex", flexDirection: "column", gap: 10, marginBottom: 22 }}>
      {projects.map(p => { const ts = tasksOf(p.taskIds); const done = ts.filter(t => t.progress === "completed").length; return <div key={p.id} style={{ background: "var(--surface-card)", border: "1px solid var(--line)", borderRadius: "var(--radius)", overflow: "hidden", boxShadow: "var(--shadow-card)" }}>
        <button onClick={() => setOpen(o => ({ ...o, [p.id]: !o[p.id] }))} style={{ display: "flex", alignItems: "center", gap: 11, width: "100%", padding: "12px 16px", border: "none", background: "transparent", textAlign: "left" }}>
          <Icon name={open[p.id] ? "chevronD" : "chevronR"} size={15} color="var(--ink-soft)" />
          <span style={{ fontWeight: 700, fontSize: 13.5 }}>{p.name}</span>
          <Badge variant="neutral">{p.theme}</Badge>
          {p.playbook && <Badge variant="accent"><Icon name="book" size={10} /> Playbook-linked</Badge>}
          <span style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 12, fontSize: 11.5, color: "var(--ink-soft)" }}><span className="tabular">{done}/{ts.length} done</span><span className="tabular">{p.start} → {p.due}</span></span>
        </button>
        {open[p.id] && <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13, borderTop: "1px solid var(--line-soft)" }}><tbody>
          {ts.map(t => <tr key={t.id}><td style={{ padding: "9px 16px 9px 42px", borderBottom: "1px solid var(--line-soft)", fontWeight: 500 }}>{t.name}</td>
            <td style={{ padding: "9px 8px", borderBottom: "1px solid var(--line-soft)" }}>{t.assignees[0] ? <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12 }}><Avatar name={t.assignees[0].name} size={20} />{t.assignees[0].name}</span> : <span style={{ color: "var(--ink-faint)", fontSize: 12 }}>Unassigned</span>}</td>
            <td style={{ padding: "9px 8px", borderBottom: "1px solid var(--line-soft)" }}><Badge variant={PRIORITY_VARIANT[t.priority]}>{t.priority}</Badge></td>
            <td style={{ padding: "9px 8px", borderBottom: "1px solid var(--line-soft)" }}><Badge variant={PROGRESS_VARIANT[t.progress]}>{VCP.PROGRESS_LABEL[t.progress]}</Badge></td>
            <td className="tabular" style={{ padding: "9px 16px 9px 8px", borderBottom: "1px solid var(--line-soft)", textAlign: "right", color: t.overdue ? "var(--danger)" : "var(--ink-muted)" }}>{t.due}</td></tr>)}
        </tbody></table>}
      </div>; })}
    </div>
    <div className="micro" style={{ marginBottom: 12 }}>Task board</div>
    <FirmWork scopeCompany={c.id} />
    <AddProjectModal open={addP} onClose={() => setAddP(false)} company={c} onCreate={addProject} />
  </div>;
}

function AddProjectModal({ open, onClose, company, onCreate }) {
  const [f, setF] = useState({ name: "", theme: "Operational", start: "2025-06-03", due: "2025-12-31" });
  const set = patch => setF(s => ({ ...s, ...patch }));
  const create = () => {
    if (!f.name.trim()) { window.vcpToast?.("Add a project name"); return; }
    onCreate({ id: "np" + Date.now(), name: f.name, theme: f.theme, company: company.id, start: f.start, due: f.due, taskIds: [] });
    window.vcpToast?.("Project created"); setF({ name: "", theme: "Operational", start: "2025-06-03", due: "2025-12-31" }); onClose();
  };
  return <Modal open={open} onClose={onClose} eyebrow={"Module B · " + company.name} title="Add project" width={460}
    footer={<><Btn variant="ghost" onClick={onClose}>Cancel</Btn><Btn icon="plus" onClick={create}>Create project</Btn></>}>
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <Field label="Project name"><TextInput value={f.name} onChange={e => set({ name: e.target.value })} placeholder="e.g. Go-to-Market Acceleration" autoFocus /></Field>
      <Field label="VCP theme"><Select value={f.theme} onChange={v => set({ theme: v })} options={VCP.PILLAR_KEYS} width="100%" /></Field>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Field label="Start date"><TextInput type="date" value={f.start} onChange={e => set({ start: e.target.value })} /></Field>
        <Field label="Due date"><TextInput type="date" value={f.due} onChange={e => set({ due: e.target.value })} /></Field>
      </div>
    </div>
  </Modal>;
}

function CompanyDocs({ c }) {
  const docs = VCP.companyDocs;
  const folders = [...new Set(docs.map(d => d.folder))];
  const [folder, setFolder] = useState("");
  const list = folder ? docs.filter(d => d.folder === folder) : docs;
  return <div>
    <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 14 }}>
      <Select value={folder} onChange={setFolder} options={folders} placeholder="All folders" />
      <div style={{ flex: 1 }} />
      <Btn size="sm" icon="upload" onClick={() => window.vcpToast?.("Upload to SharePoint (demo)")}>Upload</Btn>
    </div>
    <DocList docs={list} />
    <div style={{ marginTop: 12, fontSize: 11.5, color: "var(--ink-faint)", display: "inline-flex", gap: 6, alignItems: "center" }}><Icon name="folder" size={13} /> Backed by the company's SharePoint library</div>
  </div>;
}

function CompanyPeople({ c }) {
  const teams = c.id === "helios" ? VCP.heliosTeams : {
    management: [{ name: "Company CEO", title: "Chief Executive Officer", email: "ceo@" + c.website, phone: "+31 20 555 0000" }, { name: "Company CFO", title: "Chief Financial Officer", email: "cfo@" + c.website, phone: "+31 20 555 0001" }],
    deal: VCP.heliosTeams.deal,
  };
  const [detail, setDetail] = useState(null);
  const Section = ({ title, members, mgmt }) => <div>
    <div className="micro" style={{ marginBottom: 10 }}>{title} · {members.length}</div>
    <div style={{ background: "var(--surface-card)", border: "1px solid var(--line)", borderRadius: "var(--radius)", overflow: "hidden", boxShadow: "var(--shadow-card)", marginBottom: 20 }}>
      {members.map((m, i) => <button key={m.email} onClick={() => setDetail({ fullName: m.name, title: m.title, email: m.email, phone: m.phone, company: mgmt ? c.name : "Northbridge Capital" })} style={{ display: "flex", alignItems: "center", gap: 12, width: "100%", padding: "12px 16px", border: "none", borderBottom: i < members.length - 1 ? "1px solid var(--line-soft)" : "none", background: "transparent", textAlign: "left", cursor: "pointer" }}>
        <Avatar name={m.name} size={34} color={mgmt ? undefined : "var(--accent)"} />
        <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 13 }}>{m.name}</div><div style={{ fontSize: 11.5, color: "var(--ink-soft)" }}>{m.title}</div></div>
        <a href={"mailto:" + m.email} onClick={e => e.stopPropagation()} style={{ color: "var(--ink-soft)" }}><Icon name="mail" size={15} /></a>
        <span className="tabular" style={{ fontSize: 11.5, color: "var(--ink-soft)" }}>{m.phone}</span>
      </button>)}
    </div>
  </div>;
  return <div>
    <Section title="Management team" members={teams.management} mgmt />
    <Section title="Deal team" members={teams.deal} />
    <Drawer open={!!detail} onClose={() => setDetail(null)} width={400} eyebrow={detail && detail.company} title={detail ? detail.fullName : ""}>
      {detail && <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}><Avatar name={detail.fullName} size={48} /><div><div style={{ fontWeight: 700, fontSize: 15 }}>{detail.fullName}</div><div style={{ color: "var(--ink-muted)", fontSize: 13 }}>{detail.title}</div></div></div>
        {[["Company", detail.company], ["Email", detail.email], ["Phone", detail.phone]].map(([l, v]) => <div key={l} style={{ display: "flex", justifyContent: "space-between", padding: "9px 0", borderBottom: "1px solid var(--line-soft)" }}><span className="micro">{l}</span><span style={{ fontSize: 13 }}>{v}</span></div>)}
      </div>}
    </Drawer>
  </div>;
}

Object.assign(window, { CompanyValueCreation, CompanyCollaboration, companyMatrix, subpillarMatrix });
