// Bagel&Co — root app, ties customer + admin + tweaks together
const { useState: useStateR, useEffect: useEffectR, useMemo: useMemoR, useCallback: useCallbackR } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "lang": "lv",
  "heroVariant": "split",
  "accentTheme": "blue",
  "showHandoff": false
}/*EDITMODE-END*/;

const ACCENT_THEMES = {
  blue:   { accent: "#1D4491", accent2: "#163677", soft: "#F7C8C9", on: "#F9EEE4" },
  pink:   { accent: "#E48F92", accent2: "#C76F73", soft: "#1D4491", on: "#FFFFFF" },
  espresso:{ accent: "#1A1410", accent2: "#000000", soft: "#F7C8C9", on: "#F9EEE4" },
};

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const lang = tweaks.lang;
  const setLang = (l) => setTweak("lang", l);

  const [view, setView] = useStateR("home");
  const [location, setLocation] = useStateR("bulduri");
  // Cart is persisted to localStorage so users don't lose it on reload
  const CART_KEY = "bagelco_cart_v1";
  const [cart, setCart] = useStateR(() => {
    try { return JSON.parse(localStorage.getItem(CART_KEY) || "[]"); }
    catch { return []; }
  });
  useEffectR(() => {
    try { localStorage.setItem(CART_KEY, JSON.stringify(cart)); } catch (e) {}
  }, [cart]);
  const [openProduct, setOpenProduct] = useStateR(null);
  const [cartOpen, setCartOpen] = useStateR(false);
  const [order, setOrder] = useStateR(null);

  // Apply accent theme
  useEffectR(() => {
    const theme = ACCENT_THEMES[tweaks.accentTheme] || ACCENT_THEMES.blue;
    const r = document.documentElement.style;
    r.setProperty("--accent", theme.accent);
    r.setProperty("--accent-2", theme.accent2);
    r.setProperty("--accent-soft", theme.soft);
    r.setProperty("--on-accent", theme.on);
  }, [tweaks.accentTheme]);

  // Scroll to top on view change
  useEffectR(() => {
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [view]);

  // Hash-based admin entry: visit /#admin to open the admin panel.
  // Also keep the URL hash in sync so refresh still lands you in admin.
  useEffectR(() => {
    const applyHash = () => {
      const h = (window.location.hash || "").replace(/^#/, "");
      if (h === "admin" && view !== "admin") setView("admin");
    };
    applyHash();
    window.addEventListener("hashchange", applyHash);
    return () => window.removeEventListener("hashchange", applyHash);
  }, []);
  useEffectR(() => {
    if (view === "admin" && window.location.hash !== "#admin") {
      history.replaceState(null, "", "#admin");
    } else if (view !== "admin" && window.location.hash === "#admin") {
      history.replaceState(null, "", window.location.pathname);
    }
  }, [view]);

  // Safety net: never let scroll lock get stuck if no overlay is on screen
  useEffectR(() => {
    if (!openProduct && !cartOpen) {
      window.__scrollLockCount = 0;
      document.body.classList.remove("is-modal-open");
    }
  }, [openProduct, cartOpen, view]);

  const cartCount = cart.reduce((s, it) => s + it.qty, 0);
  const cartTotal = cart.reduce((s, it) => s + window.priceOf(it) * it.qty, 0);

  const addToCart = (it) => { setCart([...cart, it]); setCartOpen(true); };
  const removeItem = (id) => setCart(cart.filter(it => it.id !== id));
  const clearCart = () => setCart([]);
  const goCheckout = () => { setCartOpen(false); setView("checkout"); };
  const submitOrder = async (data) => {
    const number = 1248 + Math.floor(Math.random() * 30);
    const orderObj = { ...data, number };

    // Build payload for Telegram + email
    const fmtMoney = (v) => "€" + Number(v).toFixed(2);
    const loc = (window.LOCATIONS || []).find(l => l.id === data.location);
    const locName = loc?.fullName || loc?.name || data.location || "—";
    const items = (cart || []).map(it => {
      const p = window.priceOf(it) * it.qty;
      return {
        qty: it.qty,
        name: (it.name && it.name[lang]) || it.name?.lv || "?",
        variant: it.variant ? (it.variant.name?.[lang] || "") : null,
        removed: (it.removedNames || []).map(n => n[lang] || n.lv || ""),
        added:   (it.addedNames   || []).map(n => n[lang] || n.lv || ""),
        comment: it.comment || "",
        lineTotal: fmtMoney(p),
      };
    });
    const subtotal = (cart || []).reduce((s, it) => s + window.priceOf(it) * it.qty, 0);
    const total = data.total != null ? data.total : subtotal;
    const payload = {
      lang,                     // 'lv' | 'en' | 'ru' — drives the email language
      orderNumber: "B-" + number,
      customerName: data.name || "",
      phone: data.phone || "",
      email: data.email || "",
      location: data.location,  // 'bulduri' | 'pinki' — for map link in email
      locationName: locName,
      locationAddress: loc?.address?.[lang] || loc?.address?.lv || "",
      locationMapUrl: loc?.mapUrl || "",
      pickupTime: data.pickupTime || "ASAP",
      payment: "Pay at pickup",
      items,
      subtotal: fmtMoney(subtotal),
      discount: data.discount ? fmtMoney(data.discount) : "",
      promoCode: data.promoCode || "",
      tip: data.tip ? fmtMoney(data.tip) : "",
      total: fmtMoney(total),
      orderComment: data.comment || "",
    };
    // /order endpoint sends BOTH Telegram message AND receipt email server-side.
    // We AWAIT the response and only then navigate — that gives the user a
    // real "Sending..." moment instead of an abrupt cut.
    const res = await fetch("/.netlify/functions/order", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    if (!res.ok) {
      let detail = "";
      try {
        const j = await res.json();
        detail = j.error || j.hint || "";
      } catch {}
      console.warn("[order] backend returned", res.status, detail);
      const err = new Error("Order send failed: " + res.status);
      err.detail = detail;
      err.status = res.status;
      throw err;
    }
    setOrder(orderObj);
    setView("success");
    clearCart();
  };

  // Admin view is separate (full screen)
  if (view === "admin") {
    return <>
      <window.AdminApp onExit={() => setView("home")} />
      <BagelTweaksPanel tweaks={tweaks} setTweak={setTweak} />
    </>;
  }

  return (
    <>
      <window.Header lang={lang} setLang={setLang} view={view} setView={setView}
        cartCount={cartCount} openCart={() => setCartOpen(true)} />

      {view === "home" && <>
        <window.Hero lang={lang} setView={setView} heroVariant={tweaks.heroVariant} />
        <window.LocationStrip lang={lang} location={location} setLocation={setLocation} />
        <window.PopularRow lang={lang} openProduct={setOpenProduct} />
        <window.DeliveryCard lang={lang} location={location} />
        <window.TestimonialsBand lang={lang} />
        <window.LocationsSection lang={lang} setView={setView} setLocation={setLocation} />
        <window.NewsletterBand lang={lang} />
      </>}

      {view === "menu" && <>
        <window.LocationStrip lang={lang} location={location} setLocation={setLocation} />
        <window.MenuView lang={lang} openProduct={setOpenProduct} location={location} />
      </>}

      {view === "locations" && <window.LocationsSection lang={lang} setView={setView} setLocation={setLocation} />}

      {view === "about" && <window.AboutPage lang={lang} setView={setView} />}

      {view === "delivery" && <window.DeliveryPage lang={lang} location={location} setLocation={setLocation} />}

      {view === "contact" && <window.ContactPage lang={lang} />}

      {view === "checkout" && <window.Checkout lang={lang} cart={cart} location={location}
        setLocation={setLocation} onSubmit={submitOrder} setView={setView} />}

      {view === "success" && order && <window.OrderSuccess lang={lang} order={order} setView={setView} clearCart={clearCart} />}

      {view !== "checkout" && view !== "success" && (
        <window.FloatingCart lang={lang} count={cartCount} total={cartTotal} openCart={() => setCartOpen(true)} />
      )}

      <window.Footer lang={lang} setView={setView} location={location} />

      {tweaks.showHandoff && <HandoffSection />}

      {openProduct && <window.ProductModal p={openProduct} lang={lang} onClose={() => setOpenProduct(null)} addToCart={addToCart} />}
      {cartOpen && <window.CartDrawer lang={lang} cart={cart} onClose={() => setCartOpen(false)}
        removeItem={removeItem} clearCart={clearCart} goCheckout={goCheckout} location={location} setView={setView} />}

      <BagelTweaksPanel tweaks={tweaks} setTweak={setTweak} />
    </>
  );
}

function BagelTweaksPanel({ tweaks, setTweak }) {
  const TP = window.TweaksPanel;
  const TS = window.TweakSection;
  const TR = window.TweakRadio;
  const TT = window.TweakToggle;
  return (
    <TP>
      <TS label="Language" />
      <TR label="" value={tweaks.lang} onChange={v => setTweak("lang", v)}
        options={[{value:"lv",label:"LV"},{value:"en",label:"EN"},{value:"ru",label:"RU"}]} />
      <TS label="Hero variant" />
      <TR label="" value={tweaks.heroVariant} onChange={v => setTweak("heroVariant", v)}
        options={[{value:"split",label:"Split"},{value:"mosaic",label:"Mosaic"}]} />
      <TS label="Accent theme" />
      <TR label="" value={tweaks.accentTheme} onChange={v => setTweak("accentTheme", v)}
        options={[{value:"blue",label:"Blue"},{value:"pink",label:"Pink"},{value:"espresso",label:"Espresso"}]} />
      <TS label="Developer handoff" />
      <TT label="Show handoff notes" value={tweaks.showHandoff} onChange={v => setTweak("showHandoff", v)} />
    </TP>
  );
}

function HandoffSection() {
  return (
    <section className="handoff">
      <div className="container">
        <span className="eyebrow" style={{color:"#C8AE96"}}>For your developer</span>
        <h2>Handoff notes</h2>
        <p className="handoff__intro">
          This is a high-fidelity HTML design prototype. Below is everything a developer needs to turn it into the production Next.js + database build with Telegram notifications. Toggle this section off in Tweaks if you want to share the design alone.
        </p>
        <div className="handoff-grid">
          <div className="handoff-card">
            <h4>Stack recommendation</h4>
            <ul>
              <li>Next.js 14 (App Router) + TypeScript</li>
              <li>Tailwind CSS — match tokens in <code>:root</code> from this file</li>
              <li>Supabase (Postgres + Auth) for menu, orders and admin</li>
              <li>next-intl for LV/EN/RU routing &amp; hreflang</li>
              <li>next/image for photo optimization</li>
              <li>Vercel for hosting + serverless API routes</li>
            </ul>
          </div>
          <div className="handoff-card">
            <h4>Environment variables</h4>
            <pre>{`# .env.local
NEXT_PUBLIC_SITE_URL=https://bagelco.lv
SUPABASE_URL=
SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE=
TELEGRAM_BOT_TOKEN=
TELEGRAM_CHAT_ID=
ADMIN_EMAIL=
ADMIN_PASSWORD_HASH=`}</pre>
            <p>Never commit secrets. Set these in Vercel project settings.</p>
          </div>
          <div className="handoff-card">
            <h4>Product schema</h4>
            <pre>{`type Product = {
  id: string; slug: string;
  category: 'bagels'|'panini'|'combos'|'drinks'|'coffee'|'desserts';
  name: { lv: string; en: string; ru: string };
  description: { lv: string; en: string; ru: string };
  ingredients: Ingredient[];
  price: number; oldPrice?: number;
  image: string;
  available: boolean;
  popular: boolean;
  locationAvailability: { pinki: boolean; bulduri: boolean };
  preparationTimeMinutes: number;
}`}</pre>
            <p>See <code>menu-data.js</code> for the full populated dataset (all bagels, panini, drinks, coffee, desserts in LV/EN/RU).</p>
          </div>
          <div className="handoff-card">
            <h4>Telegram payload</h4>
            <pre>{`POST /api/orders
↓ on success ↓
sendMessage(chatId,
  "🥯 New Bagel&Co pickup\\n" +
  "Order: #1247\\n" +
  "Location: Bulduri\\n" +
  "Customer: Anna · +371 26 555 814\\n" +
  "Pickup: ASAP\\n\\n" +
  "1× Bagel with pastrami\\n" +
  "  Removed: tomato, red onion\\n" +
  "1× Panini with mozzarella\\n\\n" +
  "Total: €17.40\\n" +
  "Pay at pickup")`}</pre>
          </div>
          <div className="handoff-card">
            <h4>Pages &amp; routes</h4>
            <ul>
              <li><code>/</code> · Home</li>
              <li><code>/menu</code> · Menu (cat tabs, search, modal)</li>
              <li><code>/checkout</code> · Checkout</li>
              <li><code>/order/[id]</code> · Order success</li>
              <li><code>/locations</code> · Piņķi + Bulduri</li>
              <li><code>/admin</code> · Login → orders/menu/stats</li>
              <li><code>/api/orders</code> · POST creates + Telegram + DB</li>
              <li>Each route under <code>/[lang]/</code> for LV/EN/RU</li>
            </ul>
          </div>
          <div className="handoff-card">
            <h4>What's still TODO before launch</h4>
            <ul>
              <li>Final prices (owner to fill in admin)</li>
              <li>Real addresses + map embed for Piņķi &amp; Bulduri</li>
              <li>Allergen labels per item</li>
              <li>Admin auth (NextAuth or Supabase Auth)</li>
              <li>Optional later: card payment via Stripe</li>
              <li>Privacy policy, GDPR, cookie banner</li>
              <li>Order receipt email (Resend or Postmark)</li>
              <li>Lighthouse pass, image sizes audit</li>
            </ul>
          </div>
        </div>
      </div>
    </section>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
