/* ============================================================
   Page views: Home, Menu, Order, Contact.
   Each receives { brand, cart, go, t } from the app shell.
   Exports to window.
   ============================================================ */

const { useState: useS, useMemo, useEffect: useE } = React;

/* =====================  HOME  ============================== */
function HomePage({ brand, cart, go, t }) {
  const copy = brand.copy || {};
  const signatures = brand.products.filter((p) => p.tag === "Signature").slice(0, 3);
  const feat = [
    ...signatures,
    ...brand.products.filter((p) => !signatures.some((s) => s.id === p.id)),
  ].slice(0, 3);

  return (
    <main>
      <Hero brand={brand} go={go} layout={t.heroLayout} tweaks={t} />

      {/* Featured strip */}
      <section className="section feat">
        <div className="wrap">
          <div className="sec-head">
            <div>
              <p className="eyebrow">The favorites</p>
              <h2>What people come back for</h2>
            </div>
            <button className="btn btn-ghost" onClick={() => go("menu")}>
              See full menu <Icon.arrow />
            </button>
          </div>
          <div className="feat-grid">
            {feat.map((p) => (
              <button key={p.id} className="feat-card" onClick={() => go("menu")}>
                <Ph label={p.img} className="feat-img" />
                <div className="feat-meta">
                  <span>{p.name}</span>
                  <span className="tabnum muted">{money(brand.currency, p.price)}</span>
                </div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* About */}
      <section className="section about">
        <div className="wrap about-grid">
          <Ph label={brand.about.imgLabel} className="about-img" />
          <div className="about-copy">
            <p className="eyebrow">Our story</p>
            <h2>{brand.about.title}</h2>
            {brand.about.body.map((para, i) => <p key={i} className="lede muted">{para}</p>)}
            <div className="stat-row">
              {brand.about.stats.map((s, i) => (
                <div key={i} className="stat">
                  <span className="stat-n display">{s.n}</span>
                  <span className="stat-l muted">{s.l}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Reviews */}
      <section className="section reviews">
        <div className="wrap">
          <div className="rev-head">
            <div className="stars" aria-label="Five stars">
              {[0,1,2,3,4].map((i) => <Icon.star key={i} />)}
            </div>
            <p className="eyebrow center">From the regulars</p>
          </div>
          <div className="rev-grid">
            {brand.reviews.map((r, i) => (
              <figure key={i} className="rev-card">
                <blockquote>“{r.q}”</blockquote>
                <figcaption>
                  <span className="rev-a">{r.a}</span>
                  <span className="muted">{r.s}</span>
                </figcaption>
              </figure>
            ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="cta">
        <div className="wrap cta-inner">
          <div>
            <p className="eyebrow">{brand.info.note}</p>
            <h2>{copy.ctaTitle || "Ready to order?"}</h2>
          </div>
          <button className="btn btn-dark" onClick={() => go("menu")}>
            Start your order <Icon.arrow />
          </button>
        </div>
      </section>
    </main>
  );
}

function Hero({ brand, go, layout, tweaks = {} }) {
  const h = brand.hero;
  const titleLines = h.title.split("\n");
  const imageTweakStyle = {
    "--hero-img-size": `${tweaks.heroImageSize ?? 100}%`,
    "--hero-img-x": `${tweaks.heroImageX ?? 0}px`,
    "--hero-img-y": `${tweaks.heroImageY ?? 0}px`,
    "--hero-img-mobile-size": `${tweaks.heroImageMobileSize ?? 100}%`,
    "--hero-img-mobile-x": `${tweaks.heroImageMobileX ?? 0}px`,
    "--hero-img-mobile-y": `${tweaks.heroImageMobileY ?? 0}px`,
    "--hero-rotate-speed": `${tweaks.heroImageRotateSpeed ?? 90}s`,
    "--hero-rotate-origin-x": `${tweaks.heroImageRotateOriginX ?? 50}%`,
    "--hero-rotate-origin-y": `${tweaks.heroImageRotateOriginY ?? 50}%`,
  };
  const Title = () => (
    <h1 className="hero-title">
      {titleLines.map((l, i) => <span key={i} className="hero-line">{l}</span>)}
    </h1>
  );
  const Actions = () => (
    <div className="hero-actions">
      <button className="btn btn-primary" onClick={() => go("menu")}>
        View the menu <Icon.arrow />
      </button>
      <button className="btn btn-ghost" onClick={() => go("order")}>Order ahead</button>
    </div>
  );

  if (layout === "centered") {
    return (
      <section className="hero hero-centered">
        <div className="wrap hero-c-copy">
          <p className="eyebrow center">{h.kicker}</p>
          <Title />
          <p className="hero-sub muted">{h.sub}</p>
          <Actions />
        </div>
        <div className="wrap"><Ph label={h.imgLabel} className="hero-c-img" style={imageTweakStyle} /></div>
      </section>
    );
  }

  if (layout === "fullbleed") {
    return (
      <section className="hero hero-full">
        <Ph label={h.imgLabel} className="hero-full-img" style={imageTweakStyle} />
        <div className="hero-full-scrim" />
        <div className="wrap hero-full-copy">
          <p className="eyebrow center">{h.kicker}</p>
          <Title />
          <p className="hero-sub">{h.sub}</p>
          <Actions />
        </div>
      </section>
    );
  }

  // default: "split"
  return (
    <section className={`hero hero-split ${tweaks.heroImageRotate ? "hero-rotate" : ""}`}>
      <div className="wrap hero-split-inner">
        <div className="hero-split-copy">
          <p className="eyebrow">{h.kicker}</p>
          <Title />
          <p className="hero-sub muted">{h.sub}</p>
          <Actions />
        </div>
        <Ph label={h.imgLabel} className="hero-split-img" style={imageTweakStyle} />
      </div>
    </section>
  );
}

/* =====================  MENU  ============================== */
function MenuPage({ brand, cart, go, t }) {
  const copy = brand.copy || {};
  const [active, setActive] = useS("All");
  const cats = ["All", ...brand.categories];
  const shown = active === "All" ? brand.products : brand.products.filter((p) => p.cat === active);
  const count = cartCount(cart.items);
  const total = cartTotal(cart.items, brand.products);

  return (
    <main className="menu-main">
      <section className="page-head">
        <div className="wrap">
          <p className="eyebrow">The menu</p>
          <h1>{copy.menuTitle || "The menu"}</h1>
          <p className="page-head-sub muted">{brand.tagline}</p>
        </div>
      </section>

      <div className="filterbar">
        <div className="wrap filterbar-inner">
          <div className="chips" role="tablist">
            {cats.map((c) => (
              <button key={c} role="tab" aria-selected={active === c}
                      className={`chip ${active === c ? "active" : ""}`}
                      onClick={() => setActive(c)}>{c}</button>
            ))}
          </div>
          <span className="muted mono filterbar-count">{shown.length} items</span>
        </div>
      </div>

      <section className="wrap menu-section">
        <div className={`menu-grid ${t.cardStyle}`}>
          {shown.map((p) => (
            <ProductCard key={p.id} p={p} cur={brand.currency} variant={t.cardStyle}
              qty={cart.items[p.id] || 0}
              onAdd={() => cart.add(p.id, 1)}
              onSub={() => cart.setQty(p.id, (cart.items[p.id] || 0) - 1)} />
          ))}
        </div>
      </section>

      {/* sticky order bar */}
      {count > 0 && (
        <div className="orderbar">
          <div className="wrap orderbar-inner">
            <span className="orderbar-info">
              <strong className="tabnum">{count}</strong> {count === 1 ? "item" : "items"}
              <span className="orderbar-sep">·</span>
              <strong className="tabnum">{money(brand.currency, total)}</strong>
            </span>
            <button className="btn btn-primary btn-sm" onClick={() => go("order")}>
              Review order <Icon.arrow />
            </button>
          </div>
        </div>
      )}
    </main>
  );
}

/* =====================  ORDER  ============================= */
function OrderPage({ brand, cart, go }) {
  const copy = brand.copy || {};
  const lines = brand.products
    .filter((p) => cart.items[p.id])
    .map((p) => ({ ...p, qty: cart.items[p.id], line: cart.items[p.id] * p.price }));
  const count = cartCount(cart.items);
  const subtotal = cartTotal(cart.items, brand.products);
  const [placed, setPlaced] = useS(false);
  const [form, setForm] = useS({ name: "", phone: "", time: "asap", notes: "" });
  const valid = form.name.trim() && form.phone.trim() && count > 0;

  if (placed) {
    return (
      <main className="order-main">
        <div className="wrap wrap-narrow confirm">
          <div className="confirm-badge"><Icon.check /></div>
          <h1>Order received{form.name ? `, ${form.name.split(" ")[0]}` : ""}.</h1>
          <p className="lede muted">
            This is a demo, so nothing was really charged — but in the real thing,
            {copy.orderVerb || " we'd prepare it"} and text {form.phone || "you"} when it's ready
            for {form.time === "asap" ? "collection as soon as possible" : `pickup at ${form.time}`}.
          </p>
          <div className="confirm-card card">
            {lines.map((l) => (
              <div key={l.id} className="confirm-line">
                <span><span className="tabnum">{l.qty}×</span> {l.name}</span>
                <span className="tabnum">{money(brand.currency, l.line)}</span>
              </div>
            ))}
            <div className="confirm-total">
              <span>Total</span><span className="tabnum">{money(brand.currency, subtotal)}</span>
            </div>
          </div>
          <div className="confirm-actions">
            <button className="btn btn-dark" onClick={() => { cart.clear(); setPlaced(false); go("menu"); }}>
              Start a new order
            </button>
            <button className="btn btn-ghost" onClick={() => go("home")}>Back home</button>
          </div>
        </div>
      </main>
    );
  }

  return (
    <main className="order-main">
      <section className="page-head">
        <div className="wrap">
          <p className="eyebrow">Your order</p>
          <h1>Review &amp; collect</h1>
          <p className="page-head-sub muted">Check it over, add a pickup time, and you're set. Collection only.</p>
        </div>
      </section>

      {count === 0 ? (
        <div className="wrap empty">
          <Ph label={copy.emptyOrderImage || "empty order"} className="empty-img" center />
          <h2>Nothing here yet</h2>
          <p className="muted">Your order is empty. Go pick a few favorites.</p>
          <button className="btn btn-primary" onClick={() => go("menu")}>Browse the menu <Icon.arrow /></button>
        </div>
      ) : (
        <div className="wrap order-grid">
          {/* line items */}
          <div className="order-items">
            {lines.map((l) => (
              <div key={l.id} className="order-line">
                <Ph label={l.img} className="order-line-img" center />
                <div className="order-line-body">
                  <div className="order-line-head">
                    <h3>{l.name}</h3>
                    <span className="tabnum">{money(brand.currency, l.line)}</span>
                  </div>
                  <p className="muted order-line-desc">{l.desc}</p>
                  <div className="order-line-foot">
                    <Stepper qty={l.qty} size="sm"
                      onAdd={() => cart.add(l.id, 1)}
                      onSub={() => cart.setQty(l.id, l.qty - 1)} />
                    <button className="link-remove" onClick={() => cart.setQty(l.id, 0)}>Remove</button>
                  </div>
                </div>
              </div>
            ))}
          </div>

          {/* summary + details */}
          <aside className="order-side">
            <div className="card order-summary">
              <h3>Summary</h3>
              <div className="sum-rows">
                {lines.map((l) => (
                  <div key={l.id} className="sum-row">
                    <span className="muted"><span className="tabnum">{l.qty}×</span> {l.name}</span>
                    <span className="tabnum">{money(brand.currency, l.line)}</span>
                  </div>
                ))}
              </div>
              <div className="sum-total">
                <span>Total</span>
                <span className="tabnum">{money(brand.currency, subtotal)}</span>
              </div>

              <div className="form">
                <label className="field">
                  <span>Name</span>
                  <input value={form.name} placeholder="Your name"
                    onChange={(e) => setForm({ ...form, name: e.target.value })} />
                </label>
                <label className="field">
                  <span>Phone</span>
                  <input value={form.phone} placeholder="So we can text you" inputMode="tel"
                    onChange={(e) => setForm({ ...form, phone: e.target.value })} />
                </label>
                <label className="field">
                  <span>Pickup</span>
                  <select value={form.time} onChange={(e) => setForm({ ...form, time: e.target.value })}>
                    <option value="asap">As soon as possible</option>
                    <option value="30 min">In 30 minutes</option>
                    <option value="1 hour">In 1 hour</option>
                    <option value="this evening">This evening</option>
                  </select>
                </label>
                <label className="field">
                  <span>Notes <span className="muted">(optional)</span></span>
                  <textarea rows="2" value={form.notes} placeholder="Allergies, requests…"
                    onChange={(e) => setForm({ ...form, notes: e.target.value })} />
                </label>
              </div>

              <button className="btn btn-primary order-place" disabled={!valid}
                      onClick={() => { window.scrollTo(0, 0); setPlaced(true); }}>
                Place order · {money(brand.currency, subtotal)}
              </button>
              <p className="muted mono order-disclaimer">Demo only — no payment is taken.</p>
            </div>
          </aside>
        </div>
      )}
    </main>
  );
}

/* =====================  CONTACT  =========================== */
function ContactPage({ brand, go }) {
  const { info } = brand;
  const [sent, setSent] = useS(false);
  const [msg, setMsg] = useS({ name: "", email: "", body: "" });
  const ok = msg.name.trim() && msg.email.trim() && msg.body.trim();

  return (
    <main className="contact-main">
      <section className="page-head">
        <div className="wrap">
          <p className="eyebrow">Find us</p>
          <h1>Come say hello</h1>
          <p className="page-head-sub muted">{info.note}</p>
        </div>
      </section>

      <section className="wrap contact-grid">
        <div className="contact-info">
          <div className="ci-block">
            <span className="ci-icon"><Icon.pin /></span>
            <div>
              <h4>Address</h4>
              {info.address.map((l, i) => <p key={i} className="muted">{l}</p>)}
            </div>
          </div>
          <div className="ci-block">
            <span className="ci-icon"><Icon.clock /></span>
            <div>
              <h4>Hours</h4>
              {info.hours.map((h, i) => (
                <p key={i} className="muted ci-hours"><span>{h.d}</span><span>{h.h}</span></p>
              ))}
            </div>
          </div>
          <div className="ci-block">
            <span className="ci-icon"><Icon.phone /></span>
            <div>
              <h4>Get in touch</h4>
              <p className="muted">{info.phone}</p>
              <p className="muted">{info.email}</p>
            </div>
          </div>
        </div>

        <div className="contact-right">
          <Ph label="map — neighborhood, pin on location" className="contact-map" center />
          <div className="card contact-form">
            {sent ? (
              <div className="cf-sent">
                <div className="confirm-badge sm"><Icon.check /></div>
                <h3>Thanks — message sent.</h3>
                <p className="muted">We'll get back to you at {msg.email || "your email"} soon. (Demo: nothing was sent.)</p>
                <button className="btn btn-ghost btn-sm" onClick={() => { setSent(false); setMsg({ name:"", email:"", body:"" }); }}>Send another</button>
              </div>
            ) : (
              <>
                <h3>Send a message</h3>
                <div className="form">
                  <label className="field">
                    <span>Name</span>
                    <input value={msg.name} onChange={(e) => setMsg({ ...msg, name: e.target.value })} placeholder="Your name" />
                  </label>
                  <label className="field">
                    <span>Email</span>
                    <input value={msg.email} onChange={(e) => setMsg({ ...msg, email: e.target.value })} placeholder="you@email.com" inputMode="email" />
                  </label>
                  <label className="field">
                    <span>Message</span>
                    <textarea rows="4" value={msg.body} onChange={(e) => setMsg({ ...msg, body: e.target.value })} placeholder="Catering, a big order, or just to say hi…" />
                  </label>
                  <button className="btn btn-primary" disabled={!ok} onClick={() => setSent(true)}>Send message</button>
                </div>
              </>
            )}
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { HomePage, MenuPage, OrderPage, ContactPage });
