// ============================================================
// Casa IS — root app
// ============================================================
const { useState: useSt, useEffect: useEf, useRef: useRf, useCallback: useCb } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "framed",
  "accent": "#CF5527",
  "moodyMode": false,
  "headlineFont": "serif"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = [
  '#CF5527', // burnt orange
  '#7D2027', // deep red
  '#998731', // olive gold
  '#5FABC2', // sky blue
];

const HERO_VARIANTS = [
  { id: 'framed', label: 'Framed' },
  { id: 'asym', label: 'Asymmetric' },
  { id: 'bleed', label: 'Full-bleed' },
];

function App() {
  const [lang, setLang] = useSt('en');
  const [active, setActive] = useSt('home');
  const [lightbox, setLightbox] = useSt(null); // { items, index }
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const cart = useCart();
  const [cartOpen, setCartOpen] = useSt(false);

  // Apply accent + dark mode to :root
  useEf(() => {
    document.documentElement.style.setProperty('--accent', tw.accent);
  }, [tw.accent]);
  useEf(() => {
    document.documentElement.dataset.mode = tw.moodyMode ? 'dark' : 'light';
  }, [tw.moodyMode]);
  useEf(() => {
    // Headline font swap
    const v = tw.headlineFont === 'grotesk'
      ? "'Inter', 'Helvetica Neue', Helvetica, Arial, sans-serif"
      : "'Playfair Display', Georgia, serif";
    document.documentElement.style.setProperty('--serif', v);
  }, [tw.headlineFont]);

  // Handle return from Shopify checkout (?state=purchased)
  useEf(() => {
    const params = new URLSearchParams(window.location.search);
    const state = params.get('state');
    if (state === 'purchased') {
      cart.clearCart?.();
      // Clean the URL
      window.history.replaceState({}, '', window.location.pathname + window.location.hash);
      // Scroll to newsletter after a beat
      setTimeout(() => {
        const el = document.getElementById('is-house');
        if (el) el.scrollIntoView({ behavior: 'smooth' });
      }, 800);
    }
  }, []);

  // Section nav active tracking
  useEf(() => {
    const ids = NAV_ITEMS.map(n => n.id);
    const obs = new IntersectionObserver((entries) => {
      const visible = entries
        .filter(e => e.isIntersecting)
        .sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
      if (visible) setActive(visible.target.id);
    }, { rootMargin: '-30% 0px -50% 0px', threshold: [0.1, 0.3, 0.5] });
    ids.forEach((id) => {
      const el = document.getElementById(id);
      if (el) obs.observe(el);
    });
    return () => obs.disconnect();
  }, []);

  const navigate = useCb((id) => {
    const el = document.getElementById(id);
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 64;
      window.scrollTo({ top: y, behavior: 'smooth' });
    }
  }, []);

  // Lightbox handlers
  const openOriginal = (item) => {
    const idx = ORIGINALS.findIndex(o => o.id === item.id);
    if (idx >= 0) setLightbox({ items: ORIGINALS, index: idx });
    else setLightbox({ items: [item], index: 0 });
  };
  const openPrint = (item) => {
    // open within current visible items; default to all prints
    const idx = PRINTS.findIndex(p => p.id === item.id);
    if (idx >= 0) setLightbox({ items: PRINTS, index: idx });
    else setLightbox({ items: [item], index: 0 });
  };
  const openShop = (item) => {
    // try across all shop items
    const all = [...SHOP_ITEMS.cards, ...SHOP_ITEMS.prints, ...SHOP_ITEMS.originals];
    const idx = all.findIndex(o => o.id === item.id);
    setLightbox({ items: all, index: Math.max(0, idx) });
  };

  const handleCollectionsOpen = (item) => {
    // detect whether it's an Original or Print
    if (ORIGINALS.some(o => o.id === item.id)) return openOriginal(item);
    return openPrint(item);
  };

  return (
    <>
      <Nav lang={lang} setLang={setLang} active={active} onNavigate={navigate} cartCount={cart.count} onCartClick={() => setCartOpen(true)} />
      <Hero lang={lang} variant={tw.heroVariant} />
      <Collections lang={lang} onOpenItem={handleCollectionsOpen} />
      <Shop lang={lang} onOpenItem={openShop} cart={cart} />
      <IsHouse lang={lang} />
      <Commissions lang={lang} />
      <About lang={lang} />
      <Footer lang={lang} />

      {cartOpen && <CartDrawer lang={lang} cart={cart} onClose={() => setCartOpen(false)} />}

      <Lightbox
        items={lightbox?.items || []}
        index={lightbox?.index ?? null}
        lang={lang}
        cart={cart}
        onClose={() => setLightbox(null)}
        onNav={(dir) => setLightbox(lb => {
          if (!lb) return lb;
          const n = lb.items.length;
          return { ...lb, index: (lb.index + dir + n) % n };
        })}
      />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Hero">
          <TweakRadio
            label="Frame"
            value={tw.heroVariant}
            onChange={(v) => setTweak('heroVariant', v)}
            options={HERO_VARIANTS.map(v => ({ value: v.id, label: v.label }))}
          />
        </TweakSection>

        <TweakSection label="Color">
          <TweakColor
            label="Accent"
            value={tw.accent}
            onChange={(v) => setTweak('accent', v)}
            options={ACCENT_OPTIONS}
          />
          <TweakToggle
            label="Moody mode"
            value={tw.moodyMode}
            onChange={(v) => setTweak('moodyMode', v)}
          />
        </TweakSection>

        <TweakSection label="Typography">
          <TweakRadio
            label="Headlines"
            value={tw.headlineFont}
            onChange={(v) => setTweak('headlineFont', v)}
            options={[
              { value: 'serif', label: 'Serif' },
              { value: 'grotesk', label: 'Grotesk' },
            ]}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

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