// Employee portal — the "medewerker" view

const EmployeePortal = ({ toast }) => {
  const [data, setData] = React.useState(() => window.LS_mePayslips || null); // instant first paint
  const [loadErr, setLoadErr] = React.useState(null);

  React.useEffect(() => {
    // Background refresh — keeps data current without blocking first paint.
    fetch("/api/me/payslips").then(r => r.json()).then(d => {
      if (d.error) throw new Error(d.error);
      window.LS_mePayslips = d;
      setData(d);
    }).catch(e => { if (!data) setLoadErr(e.message); });
  }, []);

  const emp = data?.employee || LS_employees[0];
  const latestSlip = data?.payslips?.[0];
  const p = latestSlip ? {
    bruto: Number(latestSlip.bruto), loonheffing: Number(latestSlip.loonheffing),
    zvw: Number(latestSlip.zvw), zvw_pct: Number(latestSlip.zvw_pct),
    net: Number(latestSlip.net), arbeidskorting: Number(latestSlip.arbeidskorting),
    payslip_id: latestSlip.id,
  } : LS_computePayslip(emp);
  const allSlips = data?.payslips || [];

  const [openPdf, setOpenPdf] = React.useState(false);
  const [explainOpen, setExplainOpen] = React.useState(false);
  const [explainState, setExplainState] = React.useState("idle");
  const [explainText, setExplainText] = React.useState("");
  const [explainErr, setExplainErr] = React.useState(null);
  const [explainModel, setExplainModel] = React.useState("");
  const downloadPdf = (id) => { if (id) window.open(`/api/payslips/${id}/pdf`, "_blank"); };

  const runExplain = async () => {
    setExplainOpen(true);
    if (explainState === "ok") return; // cache across open/close
    setExplainState("loading");
    setExplainErr(null);
    try {
      const res = await window.LS_ai.explain({ payslip: p, emp, period: "april 2026" });
      setExplainText(res.explanation || "");
      setExplainModel(res.model || "");
      setExplainState("ok");
    } catch (e) {
      setExplainErr(e.message || "onbekende fout");
      setExplainState("error");
    }
  };

  const runs = allSlips.length
    ? allSlips.slice(0, 4).map(s => ({
        id: s.id, year: s.year, period: s.period, label: s.label,
        confirmed_at: s.confirmed_at, net: Number(s.net), bruto: Number(s.bruto),
      }))
    : LS_runs.slice(0, 4).map(r => ({ ...r, net: p.net, bruto: p.bruto, id: null }));

  return (
    <div style={{ minHeight: "calc(100vh - 56px)", background: "var(--bg-2)" }}>
      <div style={{ padding: "36px 32px 48px", maxWidth: 920, margin: "0 auto" }}>

        {/* Greeting */}
        <div style={{ marginBottom: 28 }}>
          <div style={{ fontSize: 12.5, color: "var(--ink-3)", fontWeight: 500, letterSpacing: 0.5, textTransform: "uppercase", marginBottom: 6 }}>Medewerkersportal · Ehold B.V.</div>
          <h1 style={{ fontSize: 32, letterSpacing: "-0.02em" }}>Welkom terug, {emp.first_name}</h1>
          <div style={{ color: "var(--ink-2)", marginTop: 4, fontSize: 14 }}>Je strook van april is beschikbaar.</div>
        </div>

        {/* Hero strook */}
        <Card pad={0} style={{ marginBottom: 22, overflow: "hidden" }}>
          <div style={{ padding: "22px 26px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
            <div>
              <Pill tone="success" dot>Nieuw · zojuist verzonden</Pill>
              <h2 style={{ fontSize: 22, marginTop: 10 }}>Loonstrook april 2026</h2>
              <div style={{ fontSize: 12.5, color: "var(--ink-3)", marginTop: 4 }}>Periode 4 · uitbetaling op <span className="num">27 april</span></div>
            </div>
            <Row style={{ gap: 8 }}>
              <Btn size="sm" variant="secondary" icon="sparkle" onClick={runExplain}>Leg uit met AI</Btn>
              <Btn size="sm" variant="secondary" icon="eye" onClick={() => setOpenPdf(true)}>Bekijk</Btn>
              <Btn size="sm" variant="primary" icon="download" onClick={() => p.payslip_id ? downloadPdf(p.payslip_id) : toast("Nog geen verzonden strook — run eerst de loonrun")}>PDF</Btn>
            </Row>
          </div>

          <div style={{ padding: "22px 26px" }}>
            {[
              { l: "Bruto", v: p.bruto, sub: `${emp.hours.toLocaleString("nl-NL", { minimumFractionDigits: 2 })} uur · ${emp.parttime}%` },
              { l: "Loonheffing", v: p.loonheffing, sub: `Witte tabel · BT ${LS_fmt.pct(emp.bt_pct)}` },
              { l: "Bijdrage ZVW", v: p.zvw, sub: LS_fmt.pct(p.zvw_pct) },
            ].map(r => (
              <Row key={r.l} style={{ justifyContent: "space-between", padding: "10px 0", borderBottom: "1px solid var(--line)" }}>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{r.l}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{r.sub}</div>
                </div>
                <span className="num" style={{ fontSize: 15 }}>{LS_fmt.eurSigned(r.v)}</span>
              </Row>
            ))}
            <Row style={{ justifyContent: "space-between", padding: "16px 0 4px" }}>
              <div>
                <div style={{ fontSize: 12, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: 0.7, fontWeight: 600 }}>Uit te betalen</div>
                <div className="num" style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{emp.iban}</div>
              </div>
              <div className="num" style={{ fontSize: 32, fontWeight: 600, letterSpacing: "-0.02em", fontFamily: "'Instrument Sans', sans-serif" }}>
                {LS_fmt.eurSigned(p.net)}
              </div>
            </Row>
          </div>
        </Card>

        {/* YTD + jaaropgave */}
        <div style={{ display: "grid", gridTemplateColumns: "1.3fr 1fr", gap: 18, marginBottom: 22 }}>
          <Section title="Dit jaar — 2026">
            <div style={{ padding: "16px 18px", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
              <Stat2 label="Totaal bruto" value={LS_fmt.eurSigned(p.bruto * 4)} />
              <Stat2 label="Loonheffing" value={LS_fmt.eurSigned(Math.abs(p.loonheffing) * 4)} />
              <Stat2 label="Totaal netto" value={LS_fmt.eurSigned(p.net * 4)} />
              <Stat2 label="Arbeidskorting (YTD)" value={LS_fmt.eurSigned(p.arbeidskorting)} />
            </div>
          </Section>
          <Section title="Jaaropgaven">
            <Row style={{ padding: "14px 18px", justifyContent: "space-between", borderBottom: "1px solid var(--line)" }}>
              <Row style={{ gap: 10 }}>
                <Icon name="pdf" size={20} style={{ color: "var(--accent)" }} />
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: 500 }}>Jaaropgave 2025</div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>gereed 28 jan 2026</div>
                </div>
              </Row>
              <Btn size="sm" variant="ghost" icon="download" />
            </Row>
            <div style={{ padding: "12px 18px", fontSize: 12, color: "var(--ink-3)" }}>Jaaropgave 2026 verschijnt in januari.</div>
          </Section>
        </div>

        {/* All stroken */}
        <Section title="Alle stroken 2026">
          {runs.map((r, i) => (
            <Row key={r.id} style={{ justifyContent: "space-between", padding: "14px 18px", borderTop: i === 0 ? "none" : "1px solid var(--line)" }}>
              <Row style={{ gap: 12 }}>
                <div style={{ width: 38, height: 38, borderRadius: 8, background: "var(--bg-2)", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
                  <div style={{ fontSize: 9, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: 0.5 }}>{["Jan","Feb","Mrt","Apr"][r.period - 1]}</div>
                  <div className="num" style={{ fontSize: 12, fontWeight: 600, lineHeight: 1 }}>'{String(r.year).slice(2)}</div>
                </div>
                <div>
                  <div style={{ fontSize: 13.5, fontWeight: 500, textTransform: "capitalize" }}>{r.label}</div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>Verzonden {LS_fmt.date(r.confirmed_at)}</div>
                </div>
              </Row>
              <Row style={{ gap: 14 }}>
                <div style={{ textAlign: "right" }}>
                  <div className="num" style={{ fontSize: 13.5, fontWeight: 500 }}>{LS_fmt.eurSigned(r.net)}</div>
                  <div style={{ fontSize: 11, color: "var(--ink-3)" }}>netto</div>
                </div>
                <Btn size="sm" variant="ghost" icon="eye" onClick={() => setOpenPdf(true)} />
                <Btn size="sm" variant="ghost" icon="download" onClick={() => r.id ? downloadPdf(r.id) : toast("Geen PDF beschikbaar")} />
              </Row>
            </Row>
          ))}
        </Section>

        {/* Settings link */}
        <Card style={{ marginTop: 22, background: "transparent", borderStyle: "dashed" }}>
          <Row style={{ gap: 12 }}>
            <Icon name="lock" size={18} style={{ color: "var(--ink-3)" }} />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500 }}>Persoonsgegevens wijzigen</div>
              <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Adres- of IBAN-wijziging wordt ter goedkeuring aan {LS_employer.legal_name} gestuurd.</div>
            </div>
            <Btn size="sm" variant="secondary">Wijzigen</Btn>
          </Row>
        </Card>
      </div>

      {/* AI explanation modal */}
      <Modal open={explainOpen} onClose={() => setExplainOpen(false)} width={620}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <Row style={{ gap: 10 }}>
            <Icon name="sparkle" size={16} style={{ color: "var(--accent)" }} />
            <div style={{ fontSize: 14, fontWeight: 600 }}>AI-uitleg van je loonstrook</div>
            <Pill tone="neutral">🔒 EU-routing</Pill>
          </Row>
          <Btn size="sm" variant="ghost" icon="x" onClick={() => setExplainOpen(false)} />
        </div>
        <div style={{ padding: "22px 24px", minHeight: 160 }}>
          {explainState === "loading" && (
            <div style={{ fontSize: 13.5, color: "var(--ink-2)" }}>AI schrijft een uitleg op maat…</div>
          )}
          {explainState === "error" && (
            <div style={{ fontSize: 13.5, color: "var(--danger)" }}>
              Kon uitleg niet ophalen: <span className="num">{explainErr}</span>
            </div>
          )}
          {explainState === "ok" && (
            <>
              <div style={{ fontSize: 14, lineHeight: 1.6, color: "var(--ink)", whiteSpace: "pre-wrap" }}>{explainText}</div>
              <div style={{ marginTop: 14, fontSize: 11, color: "var(--ink-3)" }}>Gegenereerd door <span className="num">{explainModel}</span> · AI rekent niet zelf; de cijfers komen uit de gepinde regels v2026.1.</div>
            </>
          )}
        </div>
      </Modal>

      {/* PDF modal */}
      <Modal open={openPdf} onClose={() => setOpenPdf(false)} width={820}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Loonstrook april 2026</div>
          <Row style={{ gap: 8 }}>
            <Btn size="sm" variant="ghost" icon="download" onClick={() => p.payslip_id ? downloadPdf(p.payslip_id) : toast("Geen PDF beschikbaar")} />
            <Btn size="sm" variant="ghost" icon="x" onClick={() => setOpenPdf(false)} />
          </Row>
        </div>
        <div style={{ padding: "28px 32px", background: "var(--bg-2)" }}>
          <PayslipFull emp={emp} p={p} />
        </div>
      </Modal>
    </div>
  );
};

const Stat2 = ({ label, value }) => (
  <div>
    <div style={{ fontSize: 11.5, textTransform: "uppercase", letterSpacing: 0.6, color: "var(--ink-3)", fontWeight: 500 }}>{label}</div>
    <div className="num" style={{ fontSize: 17, fontWeight: 500, marginTop: 3 }}>{value}</div>
  </div>
);

// Full payslip styled like a real Dutch loonstrook
const PayslipFull = ({ emp, p }) => (
  <div style={{ background: "#fff", border: "1px solid var(--line)", padding: 28, fontSize: 12, fontFamily: "'Inter', sans-serif" }}>
    <Row style={{ justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20 }}>
      <div>
        <div style={{ fontSize: 16, fontWeight: 700 }}>{LS_employer.legal_name}</div>
        <div className="num" style={{ fontSize: 11, color: "var(--ink-3)" }}>{LS_employer.address}, {LS_employer.postcode} {LS_employer.city}</div>
        <div className="num" style={{ fontSize: 11, color: "var(--ink-3)" }}>Loonheffingennr {LS_employer.loonheffingen_nr}</div>
      </div>
      <div style={{ textAlign: "right" }}>
        <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: 0.7, color: "var(--ink-3)" }}>Loonstrook</div>
        <div style={{ fontSize: 16, fontWeight: 600 }}>April 2026 · Periode 4</div>
      </div>
    </Row>

    <Row style={{ gap: 40, padding: "14px 0", borderTop: "1px solid var(--line)", borderBottom: "1px solid var(--line)", marginBottom: 18 }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 10, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: 0.6 }}>Medewerker</div>
        <div style={{ fontWeight: 600, marginTop: 2 }}>{emp.first_name} {emp.last_name}</div>
        <div className="num" style={{ fontSize: 11, color: "var(--ink-3)" }}>{emp.address}, {emp.postcode} {emp.city}</div>
      </div>
      <div>
        <PdfField l="Personeelsnr" v={emp.number} />
        <PdfField l="BSN" v="●●●●●●●●●" />
        <PdfField l="In dienst" v={LS_fmt.date(emp.hired_at)} />
      </div>
      <div>
        <PdfField l="Functie" v={emp.function} />
        <PdfField l="LH-tabel" v={emp.lh_table} />
        <PdfField l="Heffingskorting" v={emp.heffingskorting ? "Ja" : "Nee"} />
      </div>
    </Row>

    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 28 }}>
      <div>
        <div style={{ fontSize: 10, fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.7, color: "var(--ink-3)", marginBottom: 8 }}>Loonberekening</div>
        <PdfRow l="Basissalaris" v={emp.base_salary} sub={`${emp.hours.toLocaleString("nl-NL",{minimumFractionDigits:2})} uur`} />
        <PdfRow l="Bruto" v={p.bruto} bold rule />
        <PdfRow l="Loonheffing" v={p.loonheffing} sub={`BT ${LS_fmt.pct(emp.bt_pct)}`} />
        <PdfRow l="Bijdrage ZVW" v={p.zvw} sub={LS_fmt.pct(p.zvw_pct)} />
        <PdfRow l="Netto" v={p.net} bold rule />
      </div>
      <div>
        <div style={{ fontSize: 10, fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.7, color: "var(--ink-3)", marginBottom: 8 }}>Cumulatieven YTD</div>
        <PdfRow l="Loon loonheffing" v={p.bruto * 4} />
        <PdfRow l="Loonheffing ingehouden" v={Math.abs(p.loonheffing) * 4} />
        <PdfRow l="ZVW ingehouden" v={Math.abs(p.zvw) * 4} />
        <PdfRow l="Arbeidskorting" v={p.arbeidskorting} />
        <div style={{ marginTop: 18, padding: 12, background: "var(--bg-2)", borderRadius: 6 }}>
          <div style={{ fontSize: 10, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: 0.6 }}>Uit te betalen</div>
          <div className="num" style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.01em", marginTop: 2 }}>{LS_fmt.eurSigned(p.net)}</div>
          <div className="num" style={{ fontSize: 11, color: "var(--ink-3)" }}>{emp.iban}</div>
        </div>
      </div>
    </div>

    <div style={{ marginTop: 22, paddingTop: 14, borderTop: "1px solid var(--line)", fontSize: 10, color: "var(--ink-3)", display: "flex", justifyContent: "space-between" }}>
      <span>Gegenereerd met rekenregels v2026.1 · Brainwaive Loonstrook</span>
      <span className="num">{LS_fmt.date("2026-04-20")}</span>
    </div>
  </div>
);

const PdfField = ({ l, v }) => (
  <Row style={{ gap: 10, fontSize: 11, padding: "2px 0" }}>
    <span style={{ color: "var(--ink-3)", width: 90 }}>{l}</span>
    <span className="num" style={{ fontWeight: 500 }}>{v}</span>
  </Row>
);
const PdfRow = ({ l, v, sub, bold, rule }) => (
  <Row style={{ justifyContent: "space-between", padding: "6px 0", borderTop: rule ? "1px solid var(--ink)" : "none" }}>
    <div>
      <div style={{ fontSize: 12, fontWeight: bold ? 700 : 400 }}>{l}</div>
      {sub && <div style={{ fontSize: 10, color: "var(--ink-3)" }}>{sub}</div>}
    </div>
    <span className="num" style={{ fontSize: 12, fontWeight: bold ? 700 : 500 }}>{LS_fmt.eurSigned(v)}</span>
  </Row>
);

Object.assign(window, { EmployeePortal });
