// B2B Quote builder — line items with tier discounts, company details, delivery date,
// internal notes, submit-for-approval. Faux flow: shows "submitted" state with quote ID.

const QUOTE_TIERS = [
  { range: "1–4",   min: 1,  max: 4,   pct: 0 },
  { range: "5–9",   min: 5,  max: 9,   pct: 5 },
  { range: "10–24", min: 10, max: 24,  pct: 10 },
  { range: "25–49", min: 25, max: 49,  pct: 15 },
  { range: "50+",   min: 50, max: 999, pct: 20 },
];
const tierFor = (qty) => QUOTE_TIERS.find(tr => qty >= tr.min && qty <= tr.max) || QUOTE_TIERS[0];

function QuotePage({ lang, onBack }) {
  // Start with a typical office set
  const offices = window.PENNINN_PRODUCTS_FURNITURE.filter(p => p.kind === "office");
  const [items, setItems] = React.useState([
    { sku: "of1", qty: 10 },
    { sku: "of4", qty: 12 },
    { sku: "of7", qty: 24 },
  ]);
  const [form, setForm] = React.useState({
    company: "Acme ehf",
    kt: "581009-0210",
    contact: "Sigrún Jónsdóttir",
    email: "sigrun@acme.is",
    phone: "+354 540 2000",
    deliveryDate: "2026-06-15",
    address: "Borgartún 24, 105 Reykjavík",
    po: "",
    notes: "Uppsetning óskast á virkum dögum milli 09:00 og 16:00.",
  });
  const [submitted, setSubmitted] = React.useState(false);

  const lines = items.map(it => {
    const p = offices.find(x => x.id === it.sku);
    const base = p?.price || 0;
    const net = Math.round(base * 0.85); // B2B base net
    const tier = tierFor(it.qty);
    const unit = Math.round(net * (1 - tier.pct / 100));
    return { ...it, product: p, base, net, tier, unit, line: unit * it.qty };
  });

  const subtotal = lines.reduce((s, l) => s + l.line, 0);
  const vat = Math.round(subtotal * 0.24);
  const total = subtotal + vat;
  const baseTotal = lines.reduce((s, l) => s + l.base * l.qty, 0);
  const savings = baseTotal - subtotal;

  const setQty = (i, q) => {
    setItems(prev => prev.map((it, idx) => idx === i ? { ...it, qty: Math.max(0, Math.min(500, q)) } : it));
  };
  const removeLine = (i) => setItems(prev => prev.filter((_, idx) => idx !== i));
  const addLine = (sku) => setItems(prev => [...prev, { sku, qty: 1 }]);
  const change = (k, v) => setForm(prev => ({ ...prev, [k]: v }));

  if (submitted) {
    const quoteId = "Q-2026-" + Math.floor(1000 + Math.random() * 9000);
    return (
      <div className="quote-page shell">
        <div className="quote-success">
          <span className="quote-success-check">✓</span>
          <span className="quote-eyebrow">{t(lang,"Tilboð sent","Quote submitted")}</span>
          <h1 className="quote-h1">{t(lang,"Tilboð er á leiðinni.","Your quote is on the way.")}</h1>
          <p className="quote-lede">{t(lang,
            `Tilboðsnúmer ${quoteId} hefur verið sent á ${form.email}. Söluráðgjafi okkar staðfestir innan 24 klst og sendir undirritunarhnapp.`,
            `Quote ${quoteId} has been emailed to ${form.email}. A sales rep will confirm within 24 hours with a sign-off link.`)}</p>
          <dl className="quote-success-meta">
            <div><dt>{t(lang,"Tilboðsnúmer","Quote ID")}</dt><dd>{quoteId}</dd></div>
            <div><dt>{t(lang,"Fyrirtæki","Company")}</dt><dd>{form.company}</dd></div>
            <div><dt>{t(lang,"Upphæð án vsk","Subtotal ex VAT")}</dt><dd>{ISK(subtotal)}</dd></div>
            <div><dt>{t(lang,"Heildarverð","Total")}</dt><dd>{ISK(total)}</dd></div>
            <div><dt>{t(lang,"Afhending","Delivery")}</dt><dd>{form.deliveryDate}</dd></div>
            <div><dt>{t(lang,"Ráðgjafi","Sales rep")}</dt><dd>Halldór B. Þórisson</dd></div>
          </dl>
          <div className="quote-success-actions">
            <button className="btn-primary" onClick={() => { setSubmitted(false); }}>{t(lang,"Skoða tilboðið","View quote")}</button>
            <button className="btn-ghost" onClick={onBack}>{t(lang,"Áfram að versla","Continue shopping")}</button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="quote-page shell">
      <Crumbs items={[t(lang,"Forsíða","Home"), t(lang,"Skrifstofa","Office"), t(lang,"Tilboðsbeiðni","Request a quote")]} />
      <PDPBack onBack={onBack} lang={lang} label={t(lang,"Til baka","Back")} />

      <header className="quote-hero">
        <div>
          <span className="quote-eyebrow">▎ B2B · {t(lang,"Tilboðsbeiðni","Request a quote")}</span>
          <h1 className="quote-h1">{t(lang,"Tilboð sniðið að ykkar þörfum.","A quote built around your needs.")}</h1>
          <p className="quote-lede">{t(lang,
            "Bættu við vörum, stilltu magn — magnafsláttur reiknast sjálfkrafa. Sendu beiðni og söluráðgjafi okkar staðfestir innan 24 klst.",
            "Add products and tune quantities — volume discount applies automatically. Submit and a sales rep confirms within 24 hours.")}</p>
        </div>
        <div className="quote-hero-stats">
          <div><strong>24 klst</strong>{t(lang,"staðfesting","confirmation")}</div>
          <div><strong>30 daga</strong>{t(lang,"reikningur","invoice")}</div>
          <div><strong>10 ár</strong>{t(lang,"ábyrgð","warranty")}</div>
        </div>
      </header>

      <div className="quote-body">
        <div className="quote-main">
          <section className="quote-section">
            <header className="quote-section-head">
              <h2>{t(lang,"Vörulisti","Line items")}</h2>
              <span>{lines.length} {t(lang,"línur","lines")} · {lines.reduce((s,l) => s + l.qty, 0)} {t(lang,"stk","pcs")}</span>
            </header>

            <div className="quote-table">
              <div className="quote-table-head">
                <span>{t(lang,"Vara","Product")}</span>
                <span className="num">{t(lang,"Listaverð","List")}</span>
                <span className="num">{t(lang,"Magn","Qty")}</span>
                <span className="num">{t(lang,"Þrep","Tier")}</span>
                <span className="num">{t(lang,"Á stk","Unit")}</span>
                <span className="num">{t(lang,"Lína","Line")}</span>
                <span />
              </div>
              {lines.map((l, i) => (
                <div key={i} className="quote-row">
                  <div className="quote-row-prod">
                    <span className="quote-row-thumb" style={{ background: l.product?.swatch || "#1a1a1a" }} />
                    <div>
                      <span className="quote-row-brand">{l.product?.brand}</span>
                      <strong>{l.product?.title}</strong>
                      <span className="quote-row-variant">{l.product?.variant}</span>
                    </div>
                  </div>
                  <div className="num list">{ISK(l.base)}</div>
                  <div className="num">
                    <QtyStepper qty={l.qty} setQty={(q) => setQty(i, q)} max={500} />
                  </div>
                  <div className="num"><span className="quote-tier-tag">{l.tier.range} · {l.tier.pct === 0 ? "0%" : "−" + l.tier.pct + "%"}</span></div>
                  <div className="num"><strong>{ISK(l.unit)}</strong></div>
                  <div className="num"><strong className="quote-line-total">{ISK(l.line)}</strong></div>
                  <button className="quote-remove" onClick={() => removeLine(i)} title={t(lang,"Fjarlægja","Remove")}>×</button>
                </div>
              ))}
            </div>

            <div className="quote-add">
              <span className="pdp-eyebrow">{t(lang,"Bæta við vöru","Add product")}</span>
              <div className="quote-add-options">
                {offices.filter(p => !items.find(i => i.sku === p.id)).slice(0, 4).map(p => (
                  <button key={p.id} className="quote-add-btn" onClick={() => addLine(p.id)}>
                    <span style={{ background: p.swatch }} className="quote-add-swatch" />
                    <div>
                      <strong>{p.title}</strong>
                      <span>{p.brand} · {ISK(p.price)}</span>
                    </div>
                    <em>+</em>
                  </button>
                ))}
              </div>
            </div>
          </section>

          <section className="quote-section">
            <header className="quote-section-head">
              <h2>{t(lang,"Fyrirtæki & afhending","Company & delivery")}</h2>
            </header>
            <div className="quote-form">
              <label><span>{t(lang,"Fyrirtæki","Company")}</span><input value={form.company} onChange={(e) => change("company", e.target.value)} /></label>
              <label><span>{t(lang,"Kennitala","Reg. no")}</span><input value={form.kt} onChange={(e) => change("kt", e.target.value)} /></label>
              <label><span>{t(lang,"Tengiliður","Contact")}</span><input value={form.contact} onChange={(e) => change("contact", e.target.value)} /></label>
              <label><span>{t(lang,"Netfang","Email")}</span><input type="email" value={form.email} onChange={(e) => change("email", e.target.value)} /></label>
              <label><span>{t(lang,"Sími","Phone")}</span><input value={form.phone} onChange={(e) => change("phone", e.target.value)} /></label>
              <label><span>{t(lang,"Pöntunarnúmer (PO)","Purchase order (PO)")}</span><input value={form.po} onChange={(e) => change("po", e.target.value)} placeholder={t(lang,"Valfrjálst","Optional")} /></label>
              <label className="full"><span>{t(lang,"Afhendingaraðsetur","Delivery address")}</span><input value={form.address} onChange={(e) => change("address", e.target.value)} /></label>
              <label><span>{t(lang,"Æskileg afhending","Preferred delivery")}</span><input type="date" value={form.deliveryDate} onChange={(e) => change("deliveryDate", e.target.value)} /></label>
              <label><span>{t(lang,"Greiðsluskilmálar","Payment terms")}</span>
                <select defaultValue="30">
                  <option value="14">{t(lang,"14 daga reikningur","14-day invoice")}</option>
                  <option value="30">{t(lang,"30 daga reikningur","30-day invoice")}</option>
                  <option value="card">{t(lang,"Greiðslukort","Credit card")}</option>
                  <option value="contract">{t(lang,"Samningsskilmálar","Contract terms")}</option>
                </select>
              </label>
              <label className="full"><span>{t(lang,"Athugasemdir","Notes")}</span><textarea rows={3} value={form.notes} onChange={(e) => change("notes", e.target.value)} /></label>
            </div>
          </section>
        </div>

        <aside className="quote-summary">
          <h3>{t(lang,"Samtals","Summary")}</h3>
          <dl>
            <div><dt>{t(lang,"Listaverð","List total")}</dt><dd>{ISK(baseTotal)}</dd></div>
            <div className="ok"><dt>{t(lang,"B2B + magnafsláttur","B2B + volume")}</dt><dd>−{ISK(savings)}</dd></div>
            <div><dt>{t(lang,"Án vsk","Ex VAT")}</dt><dd>{ISK(subtotal)}</dd></div>
            <div><dt>{t(lang,"Vsk 24%","VAT 24%")}</dt><dd>{ISK(vat)}</dd></div>
            <div className="big"><dt>{t(lang,"Heild","Total")}</dt><dd>{ISK(total)}</dd></div>
          </dl>
          <div className="quote-summary-rep">
            <span className="quote-rep-avatar">HB</span>
            <div>
              <strong>Halldór B. Þórisson</strong>
              <span>{t(lang,"Söluráðgjafi · 540 2010","Sales rep · 540 2010")}</span>
            </div>
          </div>
          <button className="btn-primary quote-submit" onClick={() => setSubmitted(true)}>
            {t(lang,"Senda tilboðsbeiðni","Submit quote request")} →
          </button>
          <p className="quote-fineprint">{t(lang,
            "Engin skuldbinding við að senda inn. Verð gildir í 30 daga frá samþykkt tilboðs.",
            "No commitment to submit. Prices valid for 30 days after approval.")}
          </p>
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { QuotePage });
