// app.jsx — top-level shell. Routes between Landing / Editor / Success
// in-memory, owns the design state, and renders the Tweaks panel.

const { useState, useEffect } = React;

// Blank starting design, localized to the current language.
function makeInitialDesign(lang) {
  const base = {
    size: '30x40', zoom: 14.0, style: 'classic', frame: 'white',
    pinIcon: 'home', pinColor: '#2a3a33', pinX: 0.5, pinY: 0.5,
    showCoords: true, headlineCase: 'normal', pitch: 55, bearing: 20,
  };
  if (lang === 'en') {
    return { ...base, headline: 'Home Sweet Home', tagline: 'Where our story began', location: 'London, UK', coords: [-0.127600, 51.507400] };
  }
  return { ...base, headline: 'Nuestro hogar', tagline: 'Donde construimos nuestra historia', location: 'Madrid, España', coords: [-3.703790, 40.416775] };
}

// Language ES/EN toggle (used in the landing nav and the editor topbar).
function LangToggle() {
  const { lang, setLang } = React.useContext(window.LangContext);
  return (
    <div className="lang-toggle">
      <button className={lang === 'es' ? 'active' : ''} onClick={() => setLang('es')}>ES</button>
      <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
    </div>
  );
}
Object.assign(window, { LangToggle });

function App() {
  const [tw, setTweak] = useTweaks(window.TWEAK_DEFAULTS);
  const [lang, setLangState] = useState(window.getInitialLang());
  const t = window.makeT(lang);
  function setLang(l) {
    setLangState(l);
    try { localStorage.setItem('wismaps_lang', l); } catch (e) {}
  }

  const [route, setRoute] = useState(() => {
    const p = window.location.pathname;
    return (p === '/crear-mapa' || p === '/crear') ? 'editor' : 'landing';
  }); // landing | editor | success
  const [design, setDesign] = useState(() => makeInitialDesign(window.getInitialLang()));
  const [order, setOrder] = useState(null);
  const [checkoutOpen, setCheckoutOpen] = useState(false);

  // Cart: several maps in one order. Persisted so it survives navigation/reload.
  const [cart, setCart] = useState(() => { try { return JSON.parse(localStorage.getItem('wismaps_cart') || '[]'); } catch (e) { return []; } });
  const [cartOpen, setCartOpen] = useState(false);
  useEffect(() => { try { localStorage.setItem('wismaps_cart', JSON.stringify(cart)); } catch (e) {} }, [cart]);

  // Keep the URL in sync with the view so the editor has its own shareable link
  // (wismaps.com/crear-mapa) for ad campaigns, and the Back/Forward buttons work.
  useEffect(() => {
    let path = null;
    if (route === 'landing') path = '/';
    else if (route === 'editor') path = '/crear-mapa';
    if (path && window.location.pathname !== path) {
      window.history.pushState({ route }, '', path);
    }
  }, [route]);
  useEffect(() => {
    const onPop = () => {
      const p = window.location.pathname;
      setRoute((p === '/crear-mapa' || p === '/crear') ? 'editor' : 'landing');
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);
  function addToCart(d) { setCart(c => [...c, JSON.parse(JSON.stringify(d))]); setCartOpen(true); }
  function removeFromCart(i) { setCart(c => c.filter((_, j) => j !== i)); }

  // Local-currency pricing (detected from the browser region).
  const [currency] = useState(window.detectCurrency());
  const [price, setPrice] = useState(() => ({
    currency, amount: 19.99, unit_amount: 1999, display: window.formatMoney(19.99, currency),
  }));
  useEffect(() => {
    fetch('/api/price?currency=' + currency)
      .then(r => r.json())
      .then(p => { if (p && p.currency) setPrice({ ...p, display: window.formatMoney(p.amount, p.currency) }); })
      .catch(() => {});
  }, [currency]);

  // Apply Tweaks → body data-attrs (palette + chrome + layout + density)
  useEffect(() => {
    document.body.setAttribute('data-aesthetic', tw.aesthetic);
    document.body.setAttribute('data-chrome', tw.editorChrome);
    document.body.setAttribute('data-layout', tw.editorLayout);
    document.body.setAttribute('data-density', tw.density);
  }, [tw.aesthetic, tw.editorChrome, tw.editorLayout, tw.density]);

  function startFromTemplate(idOrIntent) {
    const tpl = window.getLocalizedTemplate(lang, idOrIntent);
    if (tpl && tpl.id) {
      setDesign(d => ({
        ...d,
        headline: tpl.headline,
        headlineCase: tpl.headlineCase || 'normal',
        tagline: tpl.tagline,
        location: tpl.location,
        coords: tpl.coords,
        style: tpl.style,
        pinIcon: tpl.pinIcon || 'pin',
        pinColor: tpl.pinColor || tpl.swatch,
        pinX: 0.5,
        pinY: 0.5,
        zoom: 14,
      }));
    }
    setRoute('editor');
  }

  function startBlank() {
    setDesign(makeInitialDesign(lang));
    setRoute('editor');
  }

  function finishOrder(o) {
    setOrder(o);
    setCheckoutOpen(false);
    setCart([]);              // order placed → empty the cart
    setRoute('success');
    window.scrollTo({ top: 0 });
  }

  return (
    <window.LangContext.Provider value={{ lang, t, setLang, currency, price }}>
      {route === 'landing' && (
        <Landing
          onStart={startBlank}
          onPickTemplate={startFromTemplate}
        />
      )}

      {route === 'editor' && (
        <Editor
          design={design}
          setDesign={setDesign}
          onBack={() => setRoute('landing')}
          onCheckout={() => addToCart(design)}
          cartCount={cart.length}
          onOpenCart={() => setCartOpen(true)}
        />
      )}

      {route === 'success' && (
        <SuccessPage
          design={design}
          order={order}
          onAgain={() => { setRoute('landing'); window.scrollTo({ top: 0 }); }}
        />
      )}

      {cartOpen && (
        <CartModal
          items={cart}
          onClose={() => setCartOpen(false)}
          onRemove={removeFromCart}
          onAddMore={() => { setCartOpen(false); setRoute('landing'); window.scrollTo({ top: 0 }); }}
          onCheckout={() => { setCartOpen(false); setCheckoutOpen(true); }}
        />
      )}

      {checkoutOpen && cart.length > 0 && (
        <CheckoutModal
          items={cart}
          onClose={() => setCheckoutOpen(false)}
          onComplete={finishOrder}
        />
      )}

      <TweaksPanel>
        <TweakSection label="Pantalla">
          <TweakSelect
            label="Ir a"
            value={route}
            options={[
              { value: 'landing', label: '1 · Landing + plantillas' },
              { value: 'editor',  label: '2 · Editor del mapa' },
              { value: 'success', label: '3 · Pago completado' },
            ]}
            onChange={v => setRoute(v)}
          />
          <TweakToggle
            label="Modal de checkout"
            value={checkoutOpen}
            onChange={v => setCheckoutOpen(v)}
          />
        </TweakSection>

        <TweakSection label="Dirección estética">
          <TweakSelect
            label="Paleta"
            value={tw.aesthetic}
            options={[
              { value: 'linen',    label: 'Linen — cálida (recomendada parejas)' },
              { value: 'forest',   label: 'Forest — terrosa (regalo familia)' },
              { value: 'midnight', label: 'Midnight — oro & negro (premium)' },
            ]}
            onChange={v => setTweak('aesthetic', v)}
          />
        </TweakSection>

        <TweakSection label="Editor">
          <TweakSelect
            label="Chrome"
            value={tw.editorChrome}
            options={[
              { value: 'light',   label: 'Claro' },
              { value: 'dark',    label: 'Oscuro' },
              { value: 'minimal', label: 'Minimalista' },
            ]}
            onChange={v => setTweak('editorChrome', v)}
          />
          <TweakSelect
            label="Layout"
            value={tw.editorLayout}
            options={[
              { value: 'sidebar',    label: 'Sidebar izquierda' },
              { value: 'rail-right', label: 'Sidebar derecha' },
            ]}
            onChange={v => setTweak('editorLayout', v)}
          />
          <TweakRadio
            label="Densidad"
            value={tw.density}
            options={['compact', 'comfy', 'spacious']}
            onChange={v => setTweak('density', v)}
          />
        </TweakSection>
      </TweaksPanel>
    </window.LangContext.Provider>
  );
}

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