// ---- Product page: personalization form + live preview --------------

// Dynamic "what happens in your book" chips
function LiveEffects({ data }) {
  const season = window.seasonFromDate(data.et);
  const ssw = window.sswToday(data.et);
  const bag = BIRTHPLACES[data.ort];
  const chips = [];
  if (data.name) chips.push({ ico: "feather", t: <>Cover und Intro für <b>{data.name}</b></> });
  if (data.et) chips.push({ ico: "calendar", t: ssw ? <>Heute <b>SSW {ssw}</b></> : <>Wochenseiten ab <b>SSW 5</b></> });
  if (season) chips.push({ ico: season === "sommer" ? "sun" : "leaf",
    t: <>Erstausstattung für ein <b>{season === "sommer" ? "Sommerbaby" : "Winterbaby"}</b></> });
  chips.push({ ico: "home", t: <b>{bag.bagTitle}</b> });
  if (data.ort === "zuhause") chips.push({ ico: "leaf", t: <>Seite <b>Mein Geburtsraum zu Hause</b></> });
  chips.push(data.photopages
    ? { ico: "image", t: <>Mit <b>Foto-Seiten</b> für Ultraschall und Babybauch</> }
    : { ico: "image", t: <><b>Ohne</b> Foto-Seiten</> });
  if (data.partner) chips.push({ ico: "users", t: <>Mit <b>{data.partner}</b> mitgedacht</> });

  return (
    <div className="j-live">
      <div className="j-live-head"><span className="j-live-dot" /> Das entsteht in deinem Buch</div>
      <div className="j-live-chips">
        {chips.map((c, i) => (
          <span key={i} className="j-live-chip">
            <Icon name={c.ico} size={14} stroke={1.6} /> {c.t}
          </span>
        ))}
      </div>
    </div>
  );
}

function Field({ label, hint, children, required, error }) {
  return (
    <div className="j-field">
      <label className="j-field-label">
        {label} {required && <span style={{ color: "var(--terracotta)" }}>*</span>}
        {hint && <span className="j-field-hint">{hint}</span>}
      </label>
      {children}
      {error && <div className="j-field-err"><Icon name="sparkle" size={12} /> {error}</div>}
    </div>
  );
}

function ConfigForm({ data, setData, errors }) {
  const set = (k, v) => setData({ ...data, [k]: v });
  return (
    <div className="j-form">
      {/* Name */}
      <Field label="Dein Name" required hint="erscheint auf dem Cover" error={errors.name}>
        <input className="j-input" value={data.name} maxLength={18} placeholder="z. B. Marie"
          onChange={(e) => set("name", e.target.value)} />
      </Field>

      {/* Farbvariante */}
      <Field label="Farbvariante" hint="Hintergrund und Schrift deines Covers">
        <div className="j-theme-row">
          {COVER_THEMES.map(t => (
            <button key={t.id} type="button" onClick={() => set("theme", t.id)}
              className={"j-theme" + (data.theme === t.id ? " is-on" : "")} title={t.label}>
              <span className="j-theme-chip" style={{ background: t.bg, color: t.name }}>
                Aa
                {data.theme === t.id && <span className="j-theme-tick" style={{ color: t.name }}><Icon name="check" size={13} stroke={3} /></span>}
              </span>
              <span className="j-theme-label">{t.label}</span>
            </button>
          ))}
        </div>
      </Field>

      {/* Geburtstermin */}
      <Field label="Voraussichtlicher Geburtstermin" required
        hint="steuert Jahreszeit und Wochenseiten" error={errors.et}>
        <input className="j-input" type="date" value={data.et}
          onChange={(e) => set("et", e.target.value)} />
      </Field>

      {/* Geburtsort */}
      <Field label="Wo möchtest du gebären?">
        <div className="j-ort-row">
          {Object.values(BIRTHPLACES).map(b => (
            <button key={b.id} type="button" onClick={() => set("ort", b.id)}
              className={"j-ort" + (data.ort === b.id ? " is-on" : "")}>
              <Icon name={b.id === "zuhause" ? "home" : b.id === "geburtshaus" ? "leaf" : "book"} size={20} stroke={1.5} />
              <span style={{ fontSize: 13.5, fontFamily: "var(--ui)", fontWeight: 600 }}>{b.label}</span>
            </button>
          ))}
        </div>
        <div className="j-ort-note"><Icon name="sparkle" size={13} /> {BIRTHPLACES[data.ort].note}</div>
      </Field>

      {/* Foto-Seiten */}
      <Field label="Foto-Seiten" hint="für Ultraschall, Babybauch und Highlight-Fotos">
        <div className="j-photo-row">
          <button type="button" onClick={() => set("photopages", true)}
            className={"j-photo" + (data.photopages ? " is-on" : "")}>
            <span className="j-photo-tick">{data.photopages && <Icon name="check" size={13} stroke={3} />}</span>
            <span>
              <span className="j-photo-t">Dazunehmen</span>
              <span className="j-photo-d">Seiten zum Einkleben deiner Bilder</span>
            </span>
          </button>
          <button type="button" onClick={() => set("photopages", false)}
            className={"j-photo" + (!data.photopages ? " is-on" : "")}>
            <span className="j-photo-tick">{!data.photopages && <Icon name="check" size={13} stroke={3} />}</span>
            <span>
              <span className="j-photo-t">Weglassen</span>
              <span className="j-photo-d">schlanker, ganz ohne Foto-Seiten</span>
            </span>
          </button>
        </div>
      </Field>

      {/* Partner */}
      <Field label="Name deines Partners oder deiner Partnerin" hint="optional">
        <input className="j-input" value={data.partner} maxLength={18} placeholder="frei lassen, wenn du allein planst"
          onChange={(e) => set("partner", e.target.value)} />
        <div style={{ fontSize: 12.5, color: "var(--ink-soft)", marginTop: 8, lineHeight: 1.5 }}>
          Lässt du das Feld frei, formulieren wir alle Stellen für dich allein.
        </div>
      </Field>
    </div>
  );
}

function BuyBox({ data, addToCart, validate }) {
  const [qty, setQty] = useState(1);
  const [added, setAdded] = useState(false);
  const onAdd = () => {
    if (!validate()) {
      document.querySelector(".j-form")?.scrollIntoView({ block: "center", behavior: "smooth" });
      return;
    }
    addToCart({ data: { ...data }, price: PRICE, qty });
    setAdded(true);
    setTimeout(() => setAdded(false), 1800);
  };
  return (
    <div className="j-buy">
      <div className="j-qtybuy">
        <div className="j-qty j-qty-lg">
          <button onClick={() => setQty(Math.max(1, qty - 1))} aria-label="weniger"><Icon name="minus" size={16} /></button>
          <span>{qty}</span>
          <button onClick={() => setQty(qty + 1)} aria-label="mehr"><Icon name="plus" size={16} /></button>
        </div>
        <Button full size="lg" onClick={onAdd} variant={added ? "terracotta" : "primary"}>
          {added ? <><Icon name="check" size={18} stroke={2.2} /> Hinzugefügt</> : <>In den Warenkorb · {eur(PRICE * qty)}</>}
        </Button>
      </div>
      <div className="j-pay">
        {["Visa", "Mastercard", "PayPal", "Klarna", "Apple Pay"].map(p => <span key={p} className="j-pay-pill">{p}</span>)}
      </div>
      <div className="j-buy-trust">
        <span><Icon name="truck" size={16} stroke={1.5} /> Lieferung in 8 bis 10 Tagen</span>
        <span><Icon name="check" size={16} stroke={1.8} /> 30 Tage Geld-zurück</span>
        <span><Icon name="book" size={16} stroke={1.5} /> Produziert in Deutschland</span>
      </div>
    </div>
  );
}

function Upsell() {
  const items = [
    { t: "Gel-Stifte Set, vier Farben", p: 9.98, ico: "feather" },
    { t: "Sticker zum Gestalten", p: 7.99, ico: "sparkle" },
    { t: "Geschenkverpackung", p: 5.99, ico: "bookmark" },
  ];
  return (
    <div style={{ marginTop: 16 }}>
      <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 24, marginBottom: 16 }}>Wird oft dazu gewählt</div>
      <div className="j-upsell">
        {items.map((it, i) => (
          <div key={i} className="j-upsell-item">
            <span className="j-upsell-ico"><Icon name={it.ico} size={20} stroke={1.5} /></span>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: "var(--ui)", fontWeight: 600, fontSize: 14, lineHeight: 1.2 }}>{it.t}</div>
              <div style={{ fontSize: 13, color: "var(--ink-soft)", marginTop: 2 }}>{eur(it.p)}</div>
            </div>
            <button className="j-add-mini" aria-label="hinzufügen"><Icon name="plus" size={16} /></button>
          </div>
        ))}
      </div>
    </div>
  );
}

function SpecsAccordion() {
  const specs = [
    { q: "Material und Verarbeitung", a: "Hardcover mit mattem Einband, vollfarbig gedruckt, mit zwei Lesebändchen." },
    { q: "Umfang und Papier", a: "Rund 105 bis 120 Seiten auf hochwertigem Papier, angenehm zu beschreiben." },
    { q: "Format", a: "Quadratisch, 20,5 × 20,5 cm. Kompakt genug für die Tasche, großzügig genug zum Schreiben." },
    { q: "Produktion und Versand", a: "Hochwertig in Deutschland produziert. Lieferung in 8 bis 10 Tagen, Versand 4,95 €." },
  ];
  const [open, setOpen] = useState(-1);
  return (
    <div style={{ marginTop: 40 }}>
      <div style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: 24, marginBottom: 8 }}>Ausstattung</div>
      {specs.map((s, i) => (
        <div key={i} className="j-faq-item" onClick={() => setOpen(open === i ? -1 : i)}>
          <div className="j-faq-q">
            <span style={{ fontFamily: "var(--ui)", fontWeight: 600, fontSize: 15.5 }}>{s.q}</span>
            <span style={{ transform: open === i ? "rotate(180deg)" : "none", transition: "transform .3s", color: "var(--terracotta)" }}>
              <Icon name="chevronD" size={18} />
            </span>
          </div>
          <div className="j-faq-a" style={{ gridTemplateRows: open === i ? "1fr" : "0fr" }}>
            <div style={{ overflow: "hidden" }}>
              <p style={{ paddingTop: 10, color: "var(--ink-soft)", lineHeight: 1.6, fontSize: 14.5 }}>{s.a}</p>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

function ProductPage({ go, data, setData, layout, addToCart }) {
  const [errors, setErrors] = useState({});
  const validate = () => {
    const e = {};
    if (!data.name.trim()) e.name = "Wir brauchen deinen Namen fürs Cover.";
    if (!data.et) e.et = "Bitte trag deinen Geburtstermin ein.";
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  useEffect(() => {
    setErrors(prev => {
      const n = { ...prev };
      if (data.name.trim()) delete n.name;
      if (data.et) delete n.et;
      return n;
    });
  }, [data.name, data.et]);

  const editorial = layout === "editorial";
  const atelier = layout === "atelier";

  return (
    <main className={"j-product " + (editorial ? "j-prod-editorial" : atelier ? "j-prod-atelier" : "j-prod-classic")}>
      <div className="j-wrap">
        <nav className="j-crumb">
          <button onClick={() => go("home")}>Start</button>
          <Icon name="chevron" size={13} />
          <span>Schwangerschaftsjournal, personalisiert</span>
        </nav>
      </div>

      <div className="j-wrap j-prod-grid">
        <div className="j-prod-visual">
          <div className="j-prod-cover-stage">
            <JournalCover data={data} scale={atelier ? 1.04 : 1} />
          </div>
          <div className="j-thumbs">
            {["Cover", "Wochenseite", "Kliniktasche", "Brief"].map((t, i) => (
              <div key={i} className={"j-thumb" + (i === 0 ? " is-on" : "")}>
                {i === 0
                  ? <div className="j-thumb-cover"><JournalCover data={data} flat /></div>
                  : <image-slot id={"prod-thumb-" + i} class="j-thumb-photo" shape="rounded" radius="6" placeholder={t}></image-slot>}
              </div>
            ))}
          </div>
          {!editorial && <LiveEffects data={data} />}
        </div>

        <div className="j-prod-info">
          <div className="j-social-proof">
            <div className="j-avastack">{["L","S","M","A"].map(a => <span key={a}>{a}</span>)}</div>
            <span style={{ fontSize: 13, color: "var(--ink-soft)" }}>Über 2.300 begleitete Schwangerschaften</span>
          </div>
          <h1 style={{ fontFamily: "var(--display)", fontWeight: 700, fontSize: "clamp(32px,3.8vw,46px)", lineHeight: 1.08, letterSpacing: "-.01em", marginTop: 14 }}>
            Schwangerschaftsjournal
          </h1>
          <p style={{ color: "var(--ink-soft)", marginTop: 12, fontSize: 16, lineHeight: 1.6, maxWidth: 470 }}>
            Dein personalisierter Begleiter durch neun Monate. Für Notizen, Termine und das, was du behalten möchtest.
          </p>
          <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 16 }}>
            <Stars value={5} size={17} />
            <span style={{ fontSize: 13.5, color: "var(--ink-soft)" }}>4,9 von 5, 2.314 Bewertungen</span>
          </div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 12, margin: "22px 0 4px" }}>
            <span style={{ fontFamily: "var(--display)", fontSize: 38, fontWeight: 700, whiteSpace: "nowrap" }}>{eur(PRICE)}</span>
            <span style={{ fontSize: 13.5, color: "var(--ink-soft)" }}>inkl. MwSt, zzgl. 4,95 € Versand</span>
          </div>

          <hr className="j-rule" />

          <ConfigForm data={data} setData={setData} errors={errors} />

          {editorial && <LiveEffects data={data} />}

          <div style={{ marginTop: 28 }}>
            <BuyBox data={data} addToCart={addToCart} validate={validate} />
          </div>

          <Upsell />
          <SpecsAccordion />
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { ProductPage });
