/* ============ Interactive Print / PDF composer ============ */
const PRINT_SECTIONS = [
  { id: 'metrics', label: 'Deal headline (KPIs)', def: true },
  { id: 'summary', label: 'Summary — property, costs, market & offer', def: true },
  { id: 'comps', label: 'Comps & ARV (+ tax records)', def: false },
  { id: 'scenarios', label: 'Scenarios (best / base / worst)', def: false },
  { id: 'caprate', label: 'Cap Rate / rental analysis', def: false },
  { id: 'mortgage', label: 'Mortgage & amortization', def: false },
  { id: 'hard', label: 'Hard Money', def: false },
  { id: 'holding', label: 'Holding costs', def: false },
  { id: 'neighborhood', label: 'Neighborhood & location', def: false },
];

function PrintComposer({ onClose, onGenerate }) {
  const [sel, setSel] = React.useState(() => { const o = {}; PRINT_SECTIONS.forEach((s) => o[s.id] = s.def); return o; });
  const toggle = (id) => setSel((s) => ({ ...s, [id]: !s[id] }));
  const all = (v) => setSel(() => { const o = {}; PRINT_SECTIONS.forEach((s) => o[s.id] = v); return o; });
  const count = Object.values(sel).filter(Boolean).length;
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" style={{ maxWidth: 560 }} onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <h2>Build PDF</h2>
          <button className="btn" onClick={onClose}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12" /></svg></button>
        </div>
        <div className="modal-body" style={{ display: 'block' }}>
          <div style={{ fontSize: 13, color: 'var(--muted)', lineHeight: 1.5, marginBottom: 14 }}>
            Choose the sections to include. Each prints exactly as it looks on screen. Then save as PDF in the print dialog.
          </div>
          <div className="print-pick">
            {PRINT_SECTIONS.map((s) => (
              <button key={s.id} className={'pick-item' + (sel[s.id] ? ' on' : '')} onClick={() => toggle(s.id)}>
                <span className="pick-box">{sel[s.id] ? <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg> : null}</span>
                {s.label}
              </button>
            ))}
          </div>
          <div className="print-presets">
            <button onClick={() => all(true)}>Select all</button>
            <button onClick={() => all(false)}>Clear</button>
          </div>
        </div>
        <div className="modal-foot">
          <div style={{ fontSize: 11.5, color: 'var(--muted)', flex: 1 }}>{count} section{count !== 1 ? 's' : ''} selected · prints landscape</div>
          <button className="btn primary" onClick={() => onGenerate(sel)} disabled={!count}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M6 9V2h12v7M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2M6 14h12v8H6z" /></svg>
            Generate PDF
          </button>
        </div>
      </div>
    </div>
  );
}

function FullPrintReport({ deal, calc, settings, sel }) {
  if (!sel) return null;
  const noop = () => {};
  const listApi = { updateList: noop, renameItem: noop, addItem: noop, removeItem: noop, resetList: noop };
  const p = deal.property;
  const today = new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
  const Sec = ({ on, title, children }) => on ? <section className="pf-sec"><div className="pf-sec-title">{title}</div>{children}</section> : null;

  return (
    <div className="print-full">
      <div className="pf-header">
        <div className="pf-brand">
          <svg viewBox="0 0 64 64" fill="none" width="34" height="34"><path d="M15 55 V25 L35 11 L35 22 L49 22 V55 Z" stroke="#15140f" strokeWidth="4.5" strokeLinejoin="round" strokeLinecap="round" /><path d="M42 31 H27 V47 H39" stroke="#b3902f" strokeWidth="4.5" strokeLinecap="round" strokeLinejoin="round" /></svg>
          <div><div className="pf-title">{(settings && settings.title) || 'Casabilia Investment'}</div><div className="pf-addr">{p.address}, {p.city}, {p.state} {p.zip}</div></div>
        </div>
        <div className="pf-date">Prepared {today}</div>
      </div>

      {sel.metrics ? (
        <div className="pf-metrics">
          {[['Purchase', fmtMoney(deal.terms.acceptedPrice)], ['Purchase Costs', fmtMoney(calc.purchaseFeesSum)], ['Rehab', fmtMoney(calc.rehabTotal)], ['ARV / Sale', fmtMoney(deal.terms.sellingPrice)], ['Selling Costs', fmtMoney(calc.sellingFeesSum)], ['Net Profit', fmtMoney(calc.netProfit)]].map((m, i) => (
            <div className="pf-metric" key={i}><div className="pm-l">{m[0]}</div><div className="pm-v">{m[1]}</div></div>
          ))}
        </div>
      ) : null}

      <Sec on={sel.summary} title="Summary"><Summary deal={deal} calc={calc} update={noop} updateList={noop} listApi={listApi} /></Sec>
      <Sec on={sel.comps} title="Comps & ARV"><CompsTab deal={deal} calc={calc} update={noop} /></Sec>
      <Sec on={sel.scenarios} title="Scenarios"><ScenariosTab deal={deal} calc={calc} update={noop} /></Sec>
      <Sec on={sel.caprate} title="Cap Rate"><CapRateCalc deal={deal} calc={calc} update={noop} /></Sec>
      <Sec on={sel.mortgage} title="Mortgage"><MortgageCalc deal={deal} calc={calc} update={noop} /></Sec>
      <Sec on={sel.hard} title="Hard Money"><HardMoneyCalc deal={deal} calc={calc} update={noop} /></Sec>
      <Sec on={sel.holding} title="Holding Costs"><HoldingTab deal={deal} calc={calc} update={noop} /></Sec>
      <Sec on={sel.neighborhood} title="Neighborhood"><NeighborhoodTab deal={deal} update={noop} /></Sec>

      <div className="pf-foot">Casabilia Investment · estimates only, not financial advice · generated {today}</div>
    </div>
  );
}

Object.assign(window, { PrintComposer, FullPrintReport });
