/* Print-only PDF document.
 *
 * Always rendered in the DOM but hidden via CSS until print media. The browser's
 * native print dialog (window.print()) becomes the PDF generator — "Save as PDF"
 * gives a clean, branded, A4 report.
 */

function PrintDoc({ result }) {
  const f = window.fmt;
  const fuel = window.SicosaEngine.FUELS[result.inputs.fuelType];
  const today = f.date();
  const i = result.inputs;
  const printDocStyles = {
    fontFamily: "var(--font-sans)",
    fontSize: 11,
    color: "#1d1e1d",
    padding: 0,
    margin: 0,
  };

  return (
    <div className="print-doc" style={printDocStyles}>
      <style>{printDocCss}</style>

      <header className="pd-header">
        <div className="pd-brand">
          <img src="assets/sicosa-logo.png" alt="" className="pd-mark" />
          <div>
            <div className="pd-brand-name">Sicosa Energy</div>
            <div className="pd-brand-sub">Wholesale petroleum & LPG · Yerevan, Armenia</div>
          </div>
        </div>
        <div className="pd-doc-meta">
          <div className="pd-doc-id">FUEL COST REPORT · v{result.formulaVersion}</div>
          <div className="pd-doc-date">{today}</div>
        </div>
      </header>

      <div className="pd-title-row">
        <div>
          <div className="pd-eyebrow">Internal margin analysis</div>
          <h1 className="pd-title">{fuel.label} · {f.amd(i.batchTons, 2)} t batch</h1>
        </div>
        <div className="pd-fuel-chip" style={{ background: fuel.color }}>
          {i.fuelType === "diesel" ? "DT" : i.fuelType === "lpg" ? "LPG" : i.fuelType === "gasoline-92" ? "92" : "95"}
        </div>
      </div>

      {/* Headline trio — Cost per liter respects the fixed-costs toggle */}
      <div className="pd-hero">
        <HeroStat
          label="Cost per liter (incl. VAT)"
          val={f.amdL(i.includeFixedCosts ? result.costPerLiterWithFixedAmd : result.costPerLiterAmd)}
          unit="AMD/L"
          sub={"$" + f.usd(i.includeFixedCosts ? result.usd.costPerLiterWithFixed : result.usd.costPerLiter, 4) + "/L · " + (i.includeFixedCosts ? "incl." : "excl.") + " fixed costs"}
        />
        <HeroStat label="Break-even price" val={f.amdL(result.breakEvenAmdPerLiter)} unit="AMD/L" sub="Zero-margin selling price" />
        <HeroStat label="Profit per batch" val={f.amd(i.includeFixedCosts ? result.profitPerBatchWithFixedAmd : result.profitPerBatchAmd)} unit="AMD" sub={"$" + f.usd(i.includeFixedCosts ? result.usd.profitPerBatchWithFixed : result.usd.profitPerBatch) + " · " + i.batchTons + " t · " + (i.includeFixedCosts ? "incl." : "excl.") + " fixed costs"} />
      </div>

      <div className="pd-grid">
        <section className="pd-section">
          <h2 className="pd-h">Inputs</h2>
          <table className="pd-table">
            <tbody>
              <tr><td>Fuel type</td><td className="r">{fuel.label}</td></tr>
              <tr><td>Batch volume</td><td className="r mono">{f.amd(i.batchTons, 2)} t</td></tr>
              <tr><td>Exchange rate</td><td className="r mono">{f.amd(i.fxRate, 2)} AMD/USD</td></tr>
              <tr><td>Density</td><td className="r mono">{f.density(i.density)} kg/L</td></tr>
              <tr><td>Purchase price (incl. delivery)</td><td className="r mono">${f.usd(i.purchasePriceUsd, 2)} /t</td></tr>
              <tr><td>Selling price (incl. VAT)</td><td className="r mono">{f.amdL(i.sellingPriceAmd)} AMD/L</td></tr>
              <tr><td>Fixed costs included</td><td className="r mono">{i.includeFixedCosts ? "Yes (260 000 AMD)" : "No"}</td></tr>
            </tbody>
          </table>
        </section>

        <section className="pd-section">
          <h2 className="pd-h">Per ton — AMD</h2>
          <table className="pd-table">
            <tbody>
              <tr><td>Cost per ton</td><td className="r mono strong">{f.amd(result.totalCostAmdPerTon)}</td></tr>
              <tr><td>VAT amount</td><td className="r mono">{f.amd(result.vatAmdPerTon)}</td></tr>
              <tr><td>Excise amount</td><td className="r mono">{f.amd(result.exciseAmdPerTon)}</td></tr>
              {result.customsAmdPerTon > 0 ? (
                <tr><td>Customs duty</td><td className="r mono">{f.amd(result.customsAmdPerTon)}</td></tr>
              ) : null}
              <tr><td>Eco tax amount</td><td className="r mono">{f.amd(result.ecoTaxAmdPerTon, 2)}</td></tr>
              <tr><td>Liters per ton</td><td className="r mono">{f.amd(result.litersPerTon, 2)} L</td></tr>
            </tbody>
          </table>
        </section>

        <section className="pd-section">
          <h2 className="pd-h">Per batch — AMD</h2>
          <table className="pd-table">
            <tbody>
              <tr><td>Total batch liters</td><td className="r mono">{f.amd(result.totalBatchLiters, 1)} L</td></tr>
              <tr><td>Total batch cost</td><td className="r mono strong">{f.amd(result.totalCostAmdPerBatch)}</td></tr>
              <tr><td>Batch revenue</td><td className="r mono">{f.amd(result.batchRevenueAmd)}</td></tr>
              <tr><td>Margin per liter</td><td className={"r mono " + (result.marginPerLiterAmd >= 0 ? "pos" : "neg")}>{f.amdL(result.marginPerLiterAmd)}</td></tr>
              <tr><td>Margin %</td><td className={"r mono " + (result.marginPct >= 0 ? "pos" : "neg")}>{(result.marginPct * 100).toFixed(2)}%</td></tr>
              <tr><td>Profit per ton</td><td className={"r mono " + (result.profitPerTonAmd >= 0 ? "pos" : "neg")}>{f.amd(result.profitPerTonAmd)}</td></tr>
              <tr><td>Profit per batch{i.includeFixedCosts ? " (incl. fixed)" : ""}</td><td className={"r mono strong " + ((i.includeFixedCosts ? result.profitPerBatchWithFixedAmd : result.profitPerBatchAmd) >= 0 ? "pos" : "neg")}>{f.amd(i.includeFixedCosts ? result.profitPerBatchWithFixedAmd : result.profitPerBatchAmd)}</td></tr>
            </tbody>
          </table>
        </section>

        <section className="pd-section">
          <h2 className="pd-h">VAT overpayment · analytical</h2>
          <table className="pd-table">
            <tbody>
              <tr><td>Overpaid VAT per liter</td><td className="r mono">{f.amdL(result.vatOverpaymentPerLiterAmd)}</td></tr>
              <tr><td>Overpaid VAT per ton</td><td className="r mono">{f.amd(result.vatOverpaymentPerTonAmd)}</td></tr>
              <tr><td>Profit after VAT overpayment</td><td className={"r mono " + (result.profitAfterVatOverpaymentAmd >= 0 ? "pos" : "neg")}>{f.amd(result.profitAfterVatOverpaymentAmd)}</td></tr>
              <tr className="hi"><td><strong>Net profit (18% profit tax)</strong></td><td className={"r mono strong " + (result.netProfitAfter18TaxAmd >= 0 ? "pos" : "neg")}>{f.amd(result.netProfitAfter18TaxAmd)}</td></tr>
            </tbody>
          </table>
        </section>
      </div>

    </div>
  );
}

function HeroStat({ label, val, unit, sub }) {
  return (
    <div className="pd-hero-stat">
      <div className="pd-hero-label">{label}</div>
      <div className="pd-hero-line">
        <span className="pd-hero-val">{val}</span>
        <span className="pd-hero-unit">{unit}</span>
      </div>
      <div className="pd-hero-sub">{sub}</div>
    </div>
  );
}

const printDocCss = `
  .pd-header {
    display: flex; justify-content: space-between; align-items: flex-start;
    padding-bottom: 14px; border-bottom: 2px solid #142031; margin-bottom: 22px;
  }
  .pd-brand { display: flex; align-items: center; gap: 12px; }
  .pd-mark { width: 38px; height: 38px; border-radius: 999px; }
  .pd-brand-name { font-family: 'Manrope', sans-serif; font-weight: 700; font-size: 16px; color: #142031; letter-spacing: -0.02em; }
  .pd-brand-sub { font-family: 'JetBrains Mono', monospace; font-size: 9.5px; color: #525352; letter-spacing: 0.08em; text-transform: uppercase; margin-top: 2px; }
  .pd-doc-meta { text-align: right; }
  .pd-doc-id { font-family: 'JetBrains Mono', monospace; font-size: 10px; letter-spacing: 0.14em; color: #2a88c1; font-weight: 600; }
  .pd-doc-date { font-family: 'JetBrains Mono', monospace; font-size: 10px; color: #525352; margin-top: 4px; letter-spacing: 0.06em; }

  .pd-title-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 18px; }
  .pd-eyebrow { font-family: 'JetBrains Mono', monospace; font-size: 10px; letter-spacing: 0.16em; color: #2a88c1; text-transform: uppercase; margin-bottom: 4px; }
  .pd-title { font-family: 'Manrope', sans-serif; font-size: 22px; font-weight: 700; letter-spacing: -0.025em; color: #142031; margin: 0; }
  .pd-fuel-chip {
    color: #fff; padding: 8px 14px; border-radius: 8px;
    font-family: 'JetBrains Mono', monospace; font-weight: 600; font-size: 13px; letter-spacing: 0.06em;
  }

  .pd-hero {
    display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;
    margin-bottom: 22px;
  }
  .pd-hero-stat {
    background: #142031; color: #fff; padding: 14px 16px; border-radius: 10px;
  }
  .pd-hero-label { font-family: 'JetBrains Mono', monospace; font-size: 8.5px; letter-spacing: 0.16em; text-transform: uppercase; color: rgba(255,255,255,0.6); }
  .pd-hero-line { display: flex; align-items: baseline; gap: 6px; margin-top: 6px; }
  .pd-hero-val { font-family: 'JetBrains Mono', monospace; font-size: 22px; font-weight: 500; letter-spacing: -0.01em; }
  .pd-hero-unit { font-family: 'JetBrains Mono', monospace; font-size: 10px; color: rgba(255,255,255,0.7); letter-spacing: 0.06em; }
  .pd-hero-sub { font-family: 'JetBrains Mono', monospace; font-size: 9px; color: rgba(255,255,255,0.7); margin-top: 4px; letter-spacing: 0.04em; }

  .pd-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 18px 22px; }
  .pd-section { break-inside: avoid; }
  .pd-h { font-family: 'JetBrains Mono', monospace; font-size: 9.5px; letter-spacing: 0.16em; text-transform: uppercase; color: #525352; font-weight: 600; margin: 0 0 8px; padding-bottom: 6px; border-bottom: 1px solid rgba(20, 32, 49, 0.14); }
  .pd-table { width: 100%; border-collapse: collapse; }
  .pd-table td { padding: 5px 0; font-size: 10.5px; border-bottom: 1px dotted rgba(20, 32, 49, 0.08); color: #1d1e1d; }
  .pd-table td.r { text-align: right; }
  .pd-table td.mono { font-family: 'JetBrains Mono', monospace; font-size: 10.5px; letter-spacing: 0.02em; color: #142031; }
  .pd-table td.strong { font-weight: 700; }
  .pd-table td.pos { color: #2f7d4f; }
  .pd-table td.neg { color: #b3422f; }
  .pd-table tr.hi td { background: #eef2f9; padding: 8px 6px; border-bottom: none; border-radius: 4px; }

`;

function exportPDF() {
  // Tiny pre-print hook for filename: change document title temporarily
  const prev = document.title;
  document.title = "Sicosa-Fuel-Cost-Report";
  window.print();
  setTimeout(() => { document.title = prev; }, 100);
}

window.PrintDoc = PrintDoc;
window.exportPDF = exportPDF;
