// Bundle builder — pick a use case, customize quantities, get a bundle discount.
// Cross-category: pulls from books + stationery + furniture + giftware catalogs.

const BUNDLES = [
  {
    id: "homeoffice",
    is: "Heimaskrifstofa", en: "Home office",
    descIs: "Allt sem þú þarft til að setja upp vinnusvæði heima. Útvalin af innanhússráðgjöfum okkar.",
    descEn: "Everything you need to set up a workspace at home. Curated by our interior consultants.",
    accent: "#1d3557",
    items: [
      { catalog: "furniture", id: "of4",  qty: 1, role: { is: "Hæðarstillanlegt borð",   en: "Standing desk" } },
      { catalog: "furniture", id: "of2",  qty: 1, role: { is: "Skrifstofustóll",        en: "Office chair" } },
      { catalog: "furniture", id: "f6",   qty: 1, role: { is: "Lýsing",                  en: "Lighting" } },
      { catalog: "stationery", id: "s1",  qty: 4, role: { is: "Pennar",                  en: "Pens" } },
      { catalog: "stationery", id: "s5",  qty: 2, role: { is: "Minnisbækur",             en: "Notebooks" } },
      { catalog: "stationery", id: "s6",  qty: 1, role: { is: "Mappa",                   en: "Binder" } },
    ],
  },
  {
    id: "apartment",
    is: "Ný íbúð", en: "New apartment",
    descIs: "Sett saman af hönnuðum okkar. Stóll, borð, lampi og smáhlutir til að byrja á.",
    descEn: "Put together by our designers. Chair, table, lamp and small items to start.",
    accent: "#3c4a36",
    items: [
      { catalog: "furniture", id: "f1",  qty: 4, role: { is: "Borðstofustólar",    en: "Dining chairs" } },
      { catalog: "furniture", id: "f5",  qty: 1, role: { is: "Loftljós",            en: "Pendant light" } },
      { catalog: "furniture", id: "f4",  qty: 1, role: { is: "Sófaborð",            en: "Coffee table" } },
      { catalog: "giftware",  id: "g6",  qty: 1, role: { is: "Vasi",                en: "Vase" } },
      { catalog: "giftware",  id: "g2",  qty: 2, role: { is: "Kertastjakar",        en: "Candle holders" } },
      { catalog: "giftware",  id: "g7",  qty: 1, role: { is: "Teppi",               en: "Throw blanket" } },
    ],
  },
  {
    id: "school",
    is: "Skólapakki", en: "Back to school",
    descIs: "5.–10. bekkur. Allt á einum listanum, pakkað í endurnýtanlegan poka.",
    descEn: "Grades 5–10. Everything on one list, packed in a reusable bag.",
    accent: "#d4751a",
    items: [
      { catalog: "stationery", id: "s1",  qty: 2, role: { is: "Pennar",         en: "Pens" } },
      { catalog: "stationery", id: "s2",  qty: 2, role: { is: "Litaðir pennar", en: "Colored pens" } },
      { catalog: "stationery", id: "s3",  qty: 3, role: { is: "Áherslupennar",  en: "Highlighters" } },
      { catalog: "stationery", id: "s4",  qty: 8, role: { is: "Post-it",        en: "Post-it" } },
      { catalog: "stationery", id: "s5",  qty: 4, role: { is: "Stílabækur",     en: "Notebooks" } },
      { catalog: "stationery", id: "s6",  qty: 2, role: { is: "Möppur",         en: "Binders" } },
      { catalog: "stationery", id: "s8",  qty: 1, role: { is: "Trélitir",       en: "Pencils" } },
    ],
  },
  {
    id: "reading",
    is: "Lesarakrókur", en: "Reading corner",
    descIs: "Stóll, lampi, teppi, og þrjár bækur valdar af ritstjórn okkar.",
    descEn: "A chair, a lamp, a throw, and three books picked by our editors.",
    accent: "#7a2230",
    items: [
      { catalog: "furniture", id: "f1",  qty: 1, role: { is: "Lesarastóll",   en: "Reading chair" } },
      { catalog: "furniture", id: "f5",  qty: 1, role: { is: "Loftljós",       en: "Pendant" } },
      { catalog: "giftware",  id: "g7",  qty: 1, role: { is: "Teppi",          en: "Throw" } },
      { catalog: "books",     id: "b1",  qty: 1, role: { is: "Skáldsaga 1",    en: "Novel 1" } },
      { catalog: "books",     id: "b3",  qty: 1, role: { is: "Skáldsaga 2",    en: "Novel 2" } },
      { catalog: "books",     id: "b6",  qty: 1, role: { is: "Spennusaga",     en: "Thriller" } },
    ],
  },
];

function lookupProduct(catalog, id) {
  if (catalog === "books") {
    return window.PENNINN_PRODUCTS.books.find(x => x.id === id);
  }
  if (catalog === "stationery") {
    return window.PENNINN_PRODUCTS_STATIONERY.find(x => x.id === id);
  }
  if (catalog === "furniture") {
    return window.PENNINN_PRODUCTS_FURNITURE.find(x => x.id === id);
  }
  if (catalog === "giftware") {
    return window.PENNINN_PRODUCTS_GIFTWARE.find(x => x.id === id);
  }
}

function BundlePage({ lang, onBack }) {
  const [activeId, setActiveId] = React.useState("homeoffice");
  const [quantities, setQuantities] = React.useState(() => {
    const init = {};
    BUNDLES.forEach(b => {
      init[b.id] = {};
      b.items.forEach(it => { init[b.id][it.catalog + ":" + it.id] = it.qty; });
    });
    return init;
  });

  const active = BUNDLES.find(b => b.id === activeId);

  const lines = active.items.map(it => {
    const p = lookupProduct(it.catalog, it.id);
    const qty = quantities[active.id][it.catalog + ":" + it.id] ?? it.qty;
    const name = p?.title || "—";
    const sub = p?.brand || p?.author || p?.variant || "";
    const unit = p?.price || 0;
    return { ...it, product: p, qty, name, sub, unit, line: unit * qty };
  });

  const subtotal = lines.reduce((s, l) => s + l.line, 0);
  const bundleDiscount = Math.round(subtotal * 0.12);
  const total = subtotal - bundleDiscount;

  const setQty = (key, q) => {
    setQuantities(prev => ({
      ...prev,
      [active.id]: { ...prev[active.id], [key]: Math.max(0, Math.min(99, q)) },
    }));
  };

  return (
    <div className="bundle-page shell">
      <Crumbs items={[t(lang,"Forsíða","Home"), t(lang,"Pakkar","Bundles"), t(lang, active.is, active.en)]} />
      <PDPBack onBack={onBack} lang={lang} label={t(lang,"Til baka","Back")} />

      <header className="bundle-hero">
        <div>
          <span className="bundle-eyebrow">▎ {t(lang,"Pakkar","Bundles")} · {t(lang,"−12% á öllu settinu","−12% on the full set")}</span>
          <h1 className="bundle-h1">
            {t(lang,
              <>Allt heimilið, <em>einn smellur.</em></>,
              <>The whole space, <em>one click.</em></>)}
          </h1>
          <p className="bundle-lede">
            {t(lang,
              "Veldu fyrirfram samsett sett og stilltu magnið. Sjáðu sparnaðinn jafnóðum. Sækja samdægurs í verslun eða sendum með uppsetningu.",
              "Pick a preset and tune the quantities. Watch the savings update live. Same-day pickup or shipped with setup.")}
          </p>
        </div>
      </header>

      <div className="bundle-tabs">
        {BUNDLES.map(b => (
          <button
            key={b.id}
            className={"bundle-tab " + (activeId === b.id ? "is-on" : "")}
            onClick={() => setActiveId(b.id)}
            style={{ "--c": b.accent }}
          >
            <strong>{t(lang, b.is, b.en)}</strong>
            <span>{b.items.length} {t(lang,"hlutar","items")}</span>
          </button>
        ))}
      </div>

      <div className="bundle-body" style={{ "--c": active.accent }}>
        <div className="bundle-items">
          <p className="bundle-desc">{t(lang, active.descIs, active.descEn)}</p>
          {lines.map(l => {
            const key = l.catalog + ":" + l.id;
            return (
              <div key={key} className={"bundle-item " + (l.qty === 0 ? "is-off" : "")}>
                <div className="bundle-item-thumb" style={{ background: l.product?.swatch || l.product?.cover ? (l.product.swatch || "#7a2230") : "#7a7468" }}>
                  <span className="bundle-item-thumb-shape" data-cat={l.catalog} />
                </div>
                <div className="bundle-item-meta">
                  <span className="bundle-item-role">{t(lang, l.role.is, l.role.en)}</span>
                  <strong>{l.name}</strong>
                  <span className="bundle-item-sub">{l.sub}</span>
                </div>
                <div className="bundle-item-price">
                  <span>{ISK(l.unit)}</span>
                  <em>{t(lang,"hver","each")}</em>
                </div>
                <div className="bundle-item-qty">
                  <QtyStepper qty={l.qty} setQty={(q) => setQty(key, q)} min={0} max={20} />
                </div>
                <div className="bundle-item-line">
                  <strong>{ISK(l.line)}</strong>
                </div>
              </div>
            );
          })}
        </div>

        <aside className="bundle-cart">
          <h3>{t(lang,"Pakkayfirlit","Bundle summary")}</h3>
          <dl className="bundle-summary">
            <div><dt>{t(lang,"Stk samtals","Items total")}</dt><dd>{lines.reduce((s,l) => s + l.qty, 0)}</dd></div>
            <div><dt>{t(lang,"Bráðabirgðasumma","Subtotal")}</dt><dd>{ISK(subtotal)}</dd></div>
            <div className="ok"><dt>{t(lang,"Pakkaafsláttur −12%","Bundle discount −12%")}</dt><dd>−{ISK(bundleDiscount)}</dd></div>
            <div className="big"><dt>{t(lang,"Samtals","Total")}</dt><dd>{ISK(total)}</dd></div>
          </dl>
          <button className="btn-primary bundle-add">
            {t(lang,"Setja pakkann í körfu","Add bundle to cart")} →
          </button>
          <ul className="bundle-promise">
            <li><span className="dot dot-green" /> {t(lang,"Sækja samdægurs í 4 verslunum","Same-day pickup in 4 stores")}</li>
            <li>→ {t(lang,"Sending 1–2 dagar, ókeypis yfir 15.000 kr","Delivery 1–2 days, free over 15,000 kr")}</li>
            <li>♢ {t(lang,"Innanhússráðgjöf í 60 mín ókeypis","60-min interior consultation free")}</li>
            <li>↺ {t(lang,"30 daga skil á öllum hlutum","30-day returns on every item")}</li>
          </ul>
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { BundlePage });
