// Print / export view with section selector

function PrintView({ state, setState, totals, tweaks }) {
  const [sel, setSel] = React.useState({
    cover: true,
    materials: true,
    hh: true,
    expenses: true,
    conditions: true,
    showMargins: false,
  });

  const presets = [
    { key: "cover-only",    label: "Solo portada (monto total)", apply: () => setSel({ cover: true, materials: false, hh: false, expenses: false, conditions: false, showMargins: false }) },
    { key: "mat-only",      label: "Solo detalle de materiales", apply: () => setSel({ cover: false, materials: true, hh: false, expenses: false, conditions: false, showMargins: false }) },
    { key: "hh-only",       label: "Solo detalle de HH",         apply: () => setSel({ cover: false, materials: false, hh: true, expenses: false, conditions: false, showMargins: false }) },
    { key: "exp-only",      label: "Solo gastos generales",       apply: () => setSel({ cover: false, materials: false, hh: false, expenses: true, conditions: false, showMargins: false }) },
    { key: "full-client",   label: "Cotización completa · cliente", apply: () => setSel({ cover: true, materials: true, hh: true, expenses: true, conditions: true, showMargins: false }) },
    { key: "full-internal", label: "Cotización completa · interna", apply: () => setSel({ cover: true, materials: true, hh: true, expenses: true, conditions: true, showMargins: true }) },
  ];

  const q = state.quote;
  const profit = q.profit || { enabled: false, visible: false, percent: 0 };

  return (
    <>
      <Topbar
        title="Imprimir / Exportar cotización"
        crumb={<>Cotización <span className="mono">{q.id}</span></>}
        actions={
          <>
            <button className="btn" onClick={() => setState(s => ({...s, route:"quote"}))}>
              ← Volver al editor
            </button>
            <button className="btn primary" onClick={() => window.print()}>
              <Icon.print /> Imprimir / PDF
            </button>
          </>
        }
      />
      <div className="print-shell">
        <aside className="print-options no-print">
          <h3>¿Qué quieres imprimir?</h3>

          <div style={{fontSize:11,color:"var(--muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:".08em",margin:"12px 0 6px"}}>Presets</div>
          <div className="stack">
            {presets.map(p => (
              <button key={p.key} className="opt" onClick={p.apply} style={{textAlign:"left",border:0,background:"transparent"}}>
                <Icon.arrow size={14} /> {p.label}
              </button>
            ))}
          </div>

          <div style={{fontSize:11,color:"var(--muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:".08em",margin:"18px 0 6px"}}>Secciones</div>
          <div className="stack">
            {[
              ["cover",      "Portada / Resumen"],
              ["materials",  "Detalle de materiales"],
              ["hh",         "Detalle de HH"],
              ["expenses",   "Gastos generales"],
              ["conditions", "Condiciones + datos bancarios"],
            ].map(([k, label]) => (
              <label key={k} className={`opt ${sel[k] ? "active" : ""}`}>
                <input type="checkbox" checked={sel[k]} onChange={e => setSel(s => ({...s, [k]: e.target.checked}))} />
                {label}
              </label>
            ))}
          </div>

          <div style={{fontSize:11,color:"var(--muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:".08em",margin:"18px 0 6px"}}>Versión</div>
          <div className="stack">
            <label className={`opt ${!sel.showMargins ? "active" : ""}`}>
              <input type="radio" name="ver" checked={!sel.showMargins}
                     onChange={() => setSel(s => ({...s, showMargins: false}))} />
              Cliente (sin márgenes)
            </label>
            <label className={`opt ${sel.showMargins ? "active" : ""}`}>
              <input type="radio" name="ver" checked={sel.showMargins}
                     onChange={() => setSel(s => ({...s, showMargins: true}))} />
              Interna (con márgenes)
            </label>
          </div>

          <div style={{marginTop:20,padding:"12px 14px",background:"var(--accent-soft)",border:"1px solid #f2d89a",borderRadius:8,fontSize:11.5,lineHeight:1.5,color:"#6b4a00"}}>
            <b>Tip:</b> Usa Cmd/Ctrl+P o el botón «Imprimir» arriba. Las páginas no seleccionadas no aparecerán en el PDF.
          </div>
        </aside>

        <div className="print-preview">
          {sel.cover      && <CoverPage q={q} totals={totals} tweaks={tweaks} profit={profit} />}
          {sel.materials  && <MaterialsPage q={q} totals={totals} tweaks={tweaks} showMargins={sel.showMargins} />}
          {sel.hh         && <HHPage q={q} totals={totals} tweaks={tweaks} showMargins={sel.showMargins} />}
          {sel.expenses && (q.expenses && q.expenses.length > 0) && <ExpensesPage q={q} totals={totals} tweaks={tweaks} />}
          {sel.conditions && <ConditionsPage q={q} tweaks={tweaks} />}
          {!sel.cover && !sel.materials && !sel.hh && !sel.expenses && !sel.conditions && (
            <div className="empty" style={{color:"#888"}}>
              <div className="ico">📄</div>
              Selecciona al menos una sección para ver la vista previa.
            </div>
          )}
        </div>
      </div>
    </>
  );
}

function PageHead({ q, tweaks, subtitle }) {
  const info = window.MAB_INFO || {};
  return (
    <div className="ph-head">
      <div className="row" style={{gap: 14, alignItems:"center"}}>
        <img className="logo" src={tweaks.logoUrl} alt="MAB"
             onError={(e)=>{e.target.style.display="none"}} />
        <div>
          <div style={{fontSize:14,fontWeight:800,letterSpacing:"-0.01em",color:"var(--brand-deep)"}}>{info.name || "MAB Automatización SpA"}</div>
          <div style={{fontSize:9.5,color:"#888",marginTop:2,letterSpacing:".04em"}}>{info.tagline || "Servicios eléctricos · Iluminación · Automatización industrial"}</div>
        </div>
      </div>
      <div className="meta">
        <div style={{fontSize:9.5,textTransform:"uppercase",letterSpacing:".08em",color:"#888"}}>Cotización</div>
        <div className="num">{q.id}</div>
        <div style={{marginTop:6}}>{subtitle}</div>
      </div>
    </div>
  );
}

function PageFoot({ q, label }) {
  const info = window.MAB_INFO || {};
  return (
    <div className="footer">
      <div>{info.name || "MAB Automatización SpA"} · {info.email || "contacto@mab-tek.pro"} · {info.phone || "+56 9 5968 1342"}</div>
      <div>{label || q.id}</div>
    </div>
  );
}

function CoverPage({ q, totals, tweaks, profit }) {
  const showProfit = profit && profit.enabled && profit.visible;
  return (
    <div className="page cover">
      <PageHead q={q} tweaks={tweaks} subtitle={`Emitida ${q.createdAt} · válida al ${q.validUntil}`} />
      <div style={{fontSize:9.5,color:"#888",textTransform:"uppercase",letterSpacing:".12em"}}>Proyecto</div>
      <h1 className="p-title">{q.projectName || "(Sin nombre de proyecto)"}</h1>

      <div className="p-section-title">Cliente</div>
      <div className="info-grid">
        <div><div className="k">Razón social</div><div className="v">{q.client.name || "—"}</div></div>
        <div><div className="k">RUT</div><div className="v">{q.client.rut || "—"}</div></div>
        <div><div className="k">Contacto</div><div className="v">{q.client.contact || "—"}</div></div>
        <div><div className="k">Email</div><div className="v">{q.client.email || "—"}</div></div>
        <div><div className="k">Teléfono</div><div className="v">{q.client.phone || "—"}</div></div>
        <div><div className="k">Dirección</div><div className="v">{q.client.address || "—"}</div></div>
      </div>

      <div className="cover-amount">
        <div className="k">Monto total {tweaks.ivaEnabled ? `(incluye IVA ${totals.ivaRate}%)` : "neto"}</div>
        <div className="v">{clp(totals.total)}</div>
        <div className="sub">Valor expresado en pesos chilenos (CLP)</div>
      </div>

      <div className="summary-grid">
        <div className="box">
          <div className="k">Materiales</div>
          <div className="v">{clp(totals.matClient)}</div>
          <div style={{fontSize:9.5,color:"#888",marginTop:4}}>{q.items.length} ítems</div>
        </div>
        <div className="box">
          <div className="k">Horas Hombre</div>
          <div className="v">{clp(totals.hhTotal)}</div>
          <div style={{fontSize:9.5,color:"#888",marginTop:4}}>{q.hh.reduce((a,h)=>a+(+h.qty||0),0)} HH · {q.hh.length} perfiles</div>
        </div>
        <div className="box">
          <div className="k">Gastos generales</div>
          <div className="v">{clp(totals.expTotal)}</div>
          <div style={{fontSize:9.5,color:"#888",marginTop:4}}>{(q.expenses||[]).length} ítems</div>
        </div>
      </div>

      {showProfit && (
        <div style={{marginTop:14,padding:"10px 14px",background:"var(--accent-soft)",border:"1px solid #f2d89a",borderRadius:8,fontSize:11,display:"flex",justifyContent:"space-between"}}>
          <span><b>Utilidad de la empresa</b> ({profit.percent}%)</span>
          <span style={{fontWeight:700}}>{clp(totals.profitAmt)}</span>
        </div>
      )}

      <div className="p-section-title" style={{marginTop:16}}>Plazo</div>
      <div style={{fontSize:10.5,lineHeight:1.6}}>
        Plazo de entrega: <b>{q.conditions.deliveryDays} días hábiles</b> desde aceptación · Validez de la oferta: <b>{q.conditions.validity} días corridos</b>.
      </div>

      {q.conditions.notes && (
        <>
          <div className="p-section-title">Alcance resumido</div>
          <div style={{fontSize:10.5, lineHeight:1.6, whiteSpace:"pre-wrap"}}>{q.conditions.notes}</div>
        </>
      )}

      <PageFoot q={q} label="Página 1 / Portada" />
    </div>
  );
}

function MaterialsPage({ q, totals, tweaks, showMargins }) {
  return (
    <div className="page">
      <PageHead q={q} tweaks={tweaks} subtitle="Detalle de materiales" />
      <h1 className="p-title">Detalle de materiales</h1>

      <table className="pt">
        <thead>
          <tr>
            <th className="c" style={{width: 40}}>#</th>
            <th style={{width: 90}}>SKU</th>
            <th>Descripción</th>
            <th className="c" style={{width: 40}}>Un.</th>
            <th className="num" style={{width: 50}}>Cant.</th>
            <th className="num" style={{width: 80}}>{showMargins ? "P. Unit." : "P. Unitario"}</th>
            {showMargins && <th className="num" style={{width: 50}}>Marg.%</th>}
            <th className="num" style={{width: 90}}>Total</th>
          </tr>
        </thead>
        <tbody>
          {q.items.map((it, idx) => {
            // Cliente: precio unitario ya incluye margen (qty × unit = total).
            // Interna: precio unitario neto + columna de margen.
            const unitShown  = showMargins ? (+it.price || 0) : (+it.price || 0) * (1 + (+it.margin || 0) / 100);
            const total      = showMargins ? itemNet(it) : itemClient(it);
            return (
              <tr key={it.id}>
                <td className="c">{idx + 1}</td>
                <td className="mono" style={{fontFamily:"var(--mono)",fontSize:9.5}}>{it.sku}</td>
                <td>{it.desc}</td>
                <td className="c">{it.unit}</td>
                <td className="num">{num(it.qty)}</td>
                <td className="num">{clp(unitShown)}</td>
                {showMargins && <td className="num">{it.margin}%</td>}
                <td className="num" style={{fontWeight:600}}>{clp(total)}</td>
              </tr>
            );
          })}
          {q.items.length === 0 && (
            <tr><td colSpan={showMargins ? 8 : 7} style={{padding:14,color:"#888",textAlign:"center"}}>Sin materiales cargados.</td></tr>
          )}
          <tr className="subtotal">
            <td colSpan={showMargins ? 7 : 6} className="num">
              {showMargins ? "Subtotal NETO (costo)" : "Subtotal materiales (cliente)"}
            </td>
            <td className="num">{clp(showMargins ? totals.matNet : totals.matClient)}</td>
          </tr>
          {showMargins && (
            <>
              <tr><td colSpan={7} className="num" style={{color:"#666"}}>Margen aplicado</td>
                  <td className="num">{clp(totals.matMarg)}</td></tr>
              <tr className="subtotal"><td colSpan={7} className="num">Total materiales al cliente</td>
                  <td className="num">{clp(totals.matClient)}</td></tr>
            </>
          )}
        </tbody>
      </table>

      <PageFoot q={q} label="Detalle materiales" />
    </div>
  );
}

function HHPage({ q, totals, tweaks, showMargins }) {
  return (
    <div className="page">
      <PageHead q={q} tweaks={tweaks} subtitle="Detalle de Horas Hombre" />
      <h1 className="p-title">Horas Hombre profesionales</h1>

      <table className="pt">
        <thead>
          <tr>
            <th className="c" style={{width: 30}}>#</th>
            <th>Rol / Perfil</th>
            <th>Alcance</th>
            <th className="num" style={{width: 50}}>HH</th>
            <th className="num" style={{width: 80}}>Valor HH</th>
            {showMargins && <th className="num" style={{width: 50}}>Ley.soc.%</th>}
            <th className="num" style={{width: 90}}>Subtotal</th>
          </tr>
        </thead>
        <tbody>
          {q.hh.map((h, idx) => {
            // Cliente: valor HH incluye leyes sociales (qty × valor = subtotal).
            // Interna: valor HH base + columna de leyes %.
            const rateShown = showMargins ? (+h.rate || 0) : (+h.rate || 0) * (1 + (+h.social || 0) / 100);
            return (
              <tr key={h.id}>
                <td className="c">{idx + 1}</td>
                <td style={{fontWeight:600}}>{h.role}</td>
                <td style={{color:"#666"}}>{h.notes || "—"}</td>
                <td className="num">{num(h.qty)}</td>
                <td className="num">{clp(rateShown)}</td>
                {showMargins && <td className="num">{h.social || 0}%</td>}
                <td className="num" style={{fontWeight:600}}>{clp(hhNet(h))}</td>
              </tr>
            );
          })}
          {q.hh.length === 0 && (
            <tr><td colSpan={showMargins ? 7 : 6} style={{padding:14,color:"#888",textAlign:"center"}}>Sin HH cargadas.</td></tr>
          )}
          {showMargins && totals.hhSocTot > 0 && (
            <>
              <tr><td colSpan={6} className="num" style={{color:"#666"}}>Base HH</td>
                  <td className="num">{clp(totals.hhBaseTot)}</td></tr>
              <tr><td colSpan={6} className="num" style={{color:"#666"}}>Leyes sociales</td>
                  <td className="num">{clp(totals.hhSocTot)}</td></tr>
            </>
          )}
          <tr className="subtotal">
            <td colSpan={showMargins ? 6 : 5} className="num">Total Horas Hombre</td>
            <td className="num">{clp(totals.hhTotal)}</td>
          </tr>
        </tbody>
      </table>

      <div style={{marginTop: 20, padding: 14, background:"#f6f6f3", borderRadius: 6, fontSize: 10, lineHeight: 1.5}}>
        <b>Nota:</b> los valores de HH corresponden a profesionales calificados de MAB Automatización SpA,
        incluyendo leyes sociales (AFP, salud, seguros, vacaciones), traslados dentro de la Región Metropolitana
        y elementos de protección personal.
      </div>

      <PageFoot q={q} label="Detalle Horas Hombre" />
    </div>
  );
}

function ExpensesPage({ q, totals, tweaks }) {
  const expenses = q.expenses || [];
  return (
    <div className="page">
      <PageHead q={q} tweaks={tweaks} subtitle="Gastos generales" />
      <h1 className="p-title">Gastos generales</h1>
      <div style={{fontSize:10.5,color:"#666",marginBottom:8,lineHeight:1.5}}>
        Arriendos, alojamientos, alimentación y demás gastos asociados a la ejecución del proyecto.
      </div>

      <table className="pt">
        <thead>
          <tr>
            <th className="c" style={{width:30}}>#</th>
            <th style={{width:160}}>Categoría</th>
            <th>Descripción</th>
            <th className="num" style={{width:50}}>Cant.</th>
            <th className="c" style={{width:50}}>Un.</th>
            <th className="num" style={{width:90}}>Valor unit.</th>
            <th className="num" style={{width:100}}>Subtotal</th>
          </tr>
        </thead>
        <tbody>
          {expenses.map((e, idx) => (
            <tr key={e.id}>
              <td className="c">{idx + 1}</td>
              <td style={{fontWeight:600}}>{e.cat}</td>
              <td style={{color:"#444"}}>{e.desc || "—"}</td>
              <td className="num">{num(e.qty)}</td>
              <td className="c">{e.unit}</td>
              <td className="num">{clp(e.price)}</td>
              <td className="num" style={{fontWeight:600}}>{clp(expenseNet(e))}</td>
            </tr>
          ))}
          <tr className="subtotal">
            <td colSpan={6} className="num">Total gastos generales</td>
            <td className="num">{clp(totals.expTotal)}</td>
          </tr>
        </tbody>
      </table>

      <PageFoot q={q} label="Gastos generales" />
    </div>
  );
}

function ConditionsPage({ q, tweaks }) {
  const info = window.MAB_INFO || {};
  const bank = info.bank || {};
  return (
    <div className="page">
      <PageHead q={q} tweaks={tweaks} subtitle="Condiciones comerciales y datos de pago" />
      <h1 className="p-title">Condiciones comerciales</h1>

      <div className="p-section-title">Forma de pago</div>
      <div style={{fontSize:10.5, lineHeight:1.6, whiteSpace:"pre-wrap"}}>{q.conditions.paymentTerms || "—"}</div>

      <div className="p-section-title">Plazos</div>
      <div className="info-grid">
        <div><div className="k">Entrega</div><div className="v">{q.conditions.deliveryDays} días hábiles</div></div>
        <div><div className="k">Validez de la oferta</div><div className="v">{q.conditions.validity} días corridos</div></div>
      </div>

      <div className="p-section-title">Garantía</div>
      <div style={{fontSize:10.5, lineHeight:1.6}}>{q.conditions.warranty}</div>

      {q.conditions.notes && (
        <>
          <div className="p-section-title">Observaciones / notas técnicas</div>
          <div style={{fontSize:10.5, lineHeight:1.6, whiteSpace:"pre-wrap"}}>{q.conditions.notes}</div>
        </>
      )}

      <div className="p-section-title">Datos para transferencia bancaria</div>
      <div style={{
        border:"1px solid #d8d6cf",
        borderRadius:8,
        padding:"12px 14px",
        background:"#FAFAF6",
        fontSize:10.5,
        lineHeight:1.65,
      }}>
        <div style={{display:"grid",gridTemplateColumns:"140px 1fr",rowGap:4}}>
          <div style={{color:"#666"}}>Razón social</div><div style={{fontWeight:600}}>{bank.holder}</div>
          <div style={{color:"#666"}}>RUT</div><div style={{fontWeight:600}}>{bank.rut}</div>
          <div style={{color:"#666"}}>Banco</div><div style={{fontWeight:600}}>{bank.bank}</div>
          <div style={{color:"#666"}}>Tipo de cuenta</div><div style={{fontWeight:600}}>{bank.account}</div>
          <div style={{color:"#666"}}>N° de cuenta</div><div style={{fontWeight:700,fontFamily:"var(--mono)",letterSpacing:".02em"}}>{bank.number}</div>
          <div style={{color:"#666"}}>Email para pagos</div><div style={{fontWeight:600}}>{bank.email}</div>
        </div>
      </div>

      <div style={{marginTop: 28, display:"grid", gridTemplateColumns:"1fr 1fr", gap: 40, fontSize: 10}}>
        <div>
          <div style={{borderTop:"1px solid #888", paddingTop:6, textAlign:"center"}}>
            <div style={{fontWeight:600}}>Por {info.name || "MAB Automatización SpA"}</div>
            <div style={{color:"#888",marginTop:2}}>Firma y timbre</div>
          </div>
        </div>
        <div>
          <div style={{borderTop:"1px solid #888", paddingTop:6, textAlign:"center"}}>
            <div style={{fontWeight:600}}>Aceptación del cliente</div>
            <div style={{color:"#888",marginTop:2}}>{q.client.name || "—"}</div>
          </div>
        </div>
      </div>

      <PageFoot q={q} label="Condiciones comerciales" />
    </div>
  );
}

Object.assign(window, { PrintView, CoverPage, MaterialsPage, HHPage, ExpensesPage, ConditionsPage });
