// ═══════════════════════════════════════════════════════════════
//  report-section.jsx — Hours Report editor + live preview (one view)
//  Presentational: state lives in app.jsx, document builder in
//  hours/report-doc.jsx. Uses shared Card/Row/Field/Select/Button.
// ═══════════════════════════════════════════════════════════════

const repCurOpts = [{ v: "EUR", l: "EUR (€)" }, { v: "BGN", l: "BGN (лв.)" }, { v: "USD", l: "USD ($)" }];

function ReportSection({ T, rep, updateRep, addRepItem, updateRepItem, removeRepItem, moveRepItem,
  invoices, onLinkInvoice, onSaveReport, onPrintReport, onDownloadReport, onNewBlank }) {

  const { useState, useEffect, useRef } = React;
  const total = sumHours(rep.items);
  const amount = total * (Number(rep.rate) || 0);

  // period quick-set: snap to the whole month of the start date
  const setMonth = () => {
    const s = rep.periodStart; if (!s) return;
    const [y, m] = s.split("-").map(Number);
    updateRep({ periodStart: `${y}-${String(m).padStart(2, "0")}-01`, periodEnd: new Date(y, m, 0).toISOString().split("T")[0] });
  };

  // self-contained preview scaling
  const previewRef = useRef(null);
  const [scale, setScale] = useState(0.62);
  useEffect(() => {
    if (!previewRef.current) return;
    const ro = new ResizeObserver(es => { const w = es[0].contentRect.width; setScale(Math.min((w - 4) / 794, 1)); });
    ro.observe(previewRef.current);
    return () => ro.disconnect();
  }, []);

  return (
    <div style={{ display: "grid", gridTemplateColumns: "minmax(400px, 1fr) minmax(340px, 0.82fr)", minHeight: "100%" }}>
      {/* ─── Editor column ─── */}
      <div style={{ padding: "22px 24px", overflow: "auto", borderRight: `1px solid ${T.line}` }}>

        <Card T={T} title="Документ" icon="clock" right={
          invoices.length > 0 && (
            <select onChange={e => { if (e.target.value !== "") onLinkInvoice(invoices[Number(e.target.value)]); e.target.value = ""; }} value=""
              style={{ padding: "5px 9px", fontSize: 11, fontFamily: MONO, border: `1px solid ${T.line}`, borderRadius: 6, background: T.field, color: T.sub, cursor: "pointer" }}>
              <option value="">Свържи с фактура…</option>
              {invoices.map((inv, i) => <option key={inv.id} value={i}>№ {inv.num} · {inv.client?.nameEn || inv.client?.name || "—"}</option>)}
            </select>
          )
        }>
          <Row>
            <Field label="Invoice №" value={rep.num} onChange={v => updateRep({ num: v })} T={T} mono minWidth={150} />
            <Select label="Валута" value={rep.currency} onChange={v => updateRep({ currency: v })} options={repCurOpts} T={T} minWidth={110} />
            <Field label="Ставка / час" type="number" value={rep.rate} onChange={v => updateRep({ rate: Number(v) || 0 })} T={T} mono minWidth={110} />
          </Row>
          <Row style={{ marginBottom: 0 }}>
            <Field label="Период от" type="date" value={rep.periodStart} onChange={v => updateRep({ periodStart: v })} T={T} minWidth={140} />
            <Field label="Период до" type="date" value={rep.periodEnd} onChange={v => updateRep({ periodEnd: v })} T={T} minWidth={140} />
            <Button T={T} kind="ghost" size="sm" icon="repeat" onClick={setMonth} style={{ marginBottom: 1 }}>Цял месец</Button>
          </Row>
        </Card>

        <Card T={T} title="Изпълнител / Клиент" icon="users">
          <Row>
            <Field label="Изпълнител" value={rep.contractorName} onChange={v => updateRep({ contractorName: v })} T={T} minWidth={180} />
            <Field label="Бележка" value={rep.contractorNote} onChange={v => updateRep({ contractorNote: v })} T={T} minWidth={180} />
          </Row>
          <Row style={{ marginBottom: 0 }}>
            <Field label="Клиент" value={rep.clientName} onChange={v => updateRep({ clientName: v })} T={T} minWidth={180} />
            <Field label="Бележка" value={rep.clientNote} onChange={v => updateRep({ clientNote: v })} T={T} minWidth={180} />
          </Row>
        </Card>

        <Card T={T} title="Дейности" icon="box" right={<Button T={T} kind="primary" size="sm" icon="plus" onClick={addRepItem}>Ред</Button>}>
          {rep.items.map((it, i) => (
            <div key={i} style={{ padding: "12px 14px", background: T.blueSoft, borderRadius: 9, marginBottom: 10 }}>
              <div style={{ display: "flex", gap: 9, alignItems: "flex-start" }}>
                <div style={{ flexShrink: 0, width: 20, textAlign: "center", fontSize: 12, fontWeight: 700, color: T.faint, paddingTop: 28 }}>{i + 1}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <TextArea label="Activity / Description" value={it.desc} onChange={v => updateRepItem(i, { desc: v })} T={T} rows={2} />
                </div>
                <div style={{ flexShrink: 0, width: 76 }}>
                  <Field label="Часове" type="number" value={it.hours} onChange={v => updateRepItem(i, { hours: Number(v) || 0 })} T={T} mono />
                </div>
                <div style={{ display: "flex", flexDirection: "column", gap: 4, paddingTop: 22 }}>
                  <button title="Нагоре" onClick={() => moveRepItem(i, -1)} style={{ background: "none", border: "none", color: T.faint, cursor: "pointer", padding: 2, transform: "rotate(-90deg)" }}><Icon name="chevron" size={14} /></button>
                  <button title="Надолу" onClick={() => moveRepItem(i, 1)} style={{ background: "none", border: "none", color: T.faint, cursor: "pointer", padding: 2, transform: "rotate(90deg)" }}><Icon name="chevron" size={14} /></button>
                  <button title="Изтрий" onClick={() => removeRepItem(i)} style={{ background: "none", border: "none", color: T.danger, cursor: "pointer", padding: 2 }}><Icon name="trash" size={15} /></button>
                </div>
              </div>
            </div>
          ))}
          <div style={{ display: "flex", justifyContent: "flex-end", gap: 28, marginTop: 14, paddingTop: 14, borderTop: `1px solid ${T.line}`, fontSize: 12.5 }}>
            <div style={{ textAlign: "right", color: T.sub, lineHeight: 1.9 }}>
              <div>Общо часове</div>
              <div style={{ fontWeight: 700, color: T.ink, fontSize: 15, marginTop: 3 }}>Сума</div>
            </div>
            <div style={{ textAlign: "right", fontFamily: MONO, lineHeight: 1.9 }}>
              <div>{fmtHours(total)}</div>
              <div style={{ fontWeight: 700, color: T.blue, fontSize: 15, marginTop: 3 }}>{fmtNum(amount)} {rep.currency}</div>
            </div>
          </div>
        </Card>

        <Card T={T} title="Подписи" icon="edit" style={{ marginBottom: 0 }}>
          <Row>
            <Field label="Изготвил — име" value={rep.preparedName} onChange={v => updateRep({ preparedName: v })} T={T} minWidth={170} />
            <Field label="Изготвил — фирма" value={rep.preparedOrg} onChange={v => updateRep({ preparedOrg: v })} T={T} minWidth={170} />
          </Row>
          <Row style={{ marginBottom: 0 }}>
            <Field label="Приел — име" value={rep.acceptedName} onChange={v => updateRep({ acceptedName: v })} T={T} minWidth={170} />
            <Field label="Приел — фирма" value={rep.acceptedOrg} onChange={v => updateRep({ acceptedOrg: v })} T={T} minWidth={170} />
          </Row>
        </Card>

      </div>

      {/* ─── Preview column ─── */}
      <div style={{ display: "flex", flexDirection: "column", background: T.bg, minWidth: 0 }}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8, padding: "14px 18px", borderBottom: `1px solid ${T.line}`, position: "sticky", top: 0, background: T.bg, zIndex: 10 }}>
          <Button T={T} kind="primary" icon="save" size="sm" onClick={onSaveReport}>Запази</Button>
          <Button T={T} kind="ghost" icon="plus" size="sm" onClick={onNewBlank}>Нов</Button>
          <div style={{ flex: 1 }} />
          <Button T={T} kind="ghost" icon="print" size="sm" onClick={onPrintReport}>Печат / PDF</Button>
          <Button T={T} kind="solid" icon="download" size="sm" onClick={onDownloadReport}>HTML</Button>
        </div>
        <div ref={previewRef} style={{ flex: 1, overflow: "auto", padding: 18, display: "flex", justifyContent: "center", alignItems: "flex-start" }}>
          <ReportDoc d={rep} scale={scale} />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ReportSection });
