// Ciao Bella — main app shell

const { useState: useStateA, useEffect: useEffectA } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "headline": "b",
  "showBundles": true,
  "showTestimonials": true
}/*EDITMODE-END*/;

function App() {
  // ── Store promo code from URL into sessionStorage on any page load ──
  useEffectA(() => {
    try {
      const hash = window.location.hash || '';
      const qIndex = hash.indexOf('?');
      if (qIndex !== -1) {
        const params = new URLSearchParams(hash.slice(qIndex + 1));
        const promo = params.get('promo');
        if (promo) sessionStorage.setItem('cb_promo', promo);
      }
    } catch(e) {}
  }, []);

  // Routing via hash
  const [route, setRoute] = useStateA(() => {
    const h = window.location.hash.replace(/^#/, '');
    return h.startsWith('/') ? h : '/';
  });
  const [tweaks, setTweaks] = useStateA(TWEAK_DEFAULTS);

  useEffectA(() => {
    const onHash = () => {
      const h = window.location.hash.replace(/^#/, '');
      setRoute(h.startsWith('/') ? h : '/');
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const navigate = (path) => {
    window.location.hash = path;
  };

  // Parse query params off route (e.g. /preorder?qty=2)
  const [pathOnly, queryStr] = route.split('?');
  const params = new URLSearchParams(queryStr || '');

  // ── Tweak protocol setup ──
  useEffectA(() => {
    function onMessage(e) {
      if (!e.data || typeof e.data !== 'object') return;
      if (e.data.type === '__activate_edit_mode') setEditOpen(true);
      if (e.data.type === '__deactivate_edit_mode') setEditOpen(false);
    }
    window.addEventListener('message', onMessage);
    window.parent.postMessage({ type: '__edit_mode_available' }, '*');
    return () => window.removeEventListener('message', onMessage);
  }, []);
  const [editOpen, setEditOpen] = useStateA(false);
  const updateTweak = (key, value) => {
    setTweaks(prev => {
      const next = { ...prev, [key]: value };
      window.parent.postMessage({ type: '__edit_mode_set_keys', edits: { [key]: value } }, '*');
      return next;
    });
  };

  // Read Stripe redirect params from main URL (Afterpay/Zip append to root URL not hash)
  const mainUrlParams = new URLSearchParams(window.location.search);
  const stripeRedirectStatus = mainUrlParams.get('redirect_status');
  const stripePaymentIntent = mainUrlParams.get('payment_intent');
  const isStripeRedirect = Boolean(stripeRedirectStatus && stripePaymentIntent);

  // If Stripe redirected back, force route to /preorder
  const effectivePathOnly = isStripeRedirect ? '/preorder' : pathOnly;

  let page;
  if (effectivePathOnly === '/preorder') {
    const qty = parseInt(params.get('qty') || '1', 10);
    const stepParam = params.get('step') === 'checkout' ? 'checkout' : 'configure';
    page = <PreorderPage
      navigate={navigate}
      tweaks={tweaks}
      initialQty={Math.max(1, Math.min(5, qty))}
      initialStep={stepParam}
      key={qty + ':' + stepParam}
    />;
  } else if (effectivePathOnly === '/about') {
    page = <AboutPage navigate={navigate} />;
  } else if (effectivePathOnly === '/for-parents') {
    page = <ForParentsPage navigate={navigate} />;
  } else if (effectivePathOnly === '/subscriptions') {
    page = <SubscriptionsPage navigate={navigate} />;
  } else if (effectivePathOnly === '/parent-app') {
    page = <ParentAppPage navigate={navigate} />;
  } else if (effectivePathOnly === '/contact') {
    page = <ContactPage navigate={navigate} />;
  } else if (effectivePathOnly === '/privacy') {
    page = <PrivacyPage navigate={navigate} />;
  } else if (effectivePathOnly === '/terms') {
    page = <TermsPage navigate={navigate} />;
  } else if (effectivePathOnly === '/refunds') {
    page = <RefundsPage navigate={navigate} />;
  } else if (effectivePathOnly === '/phone') {
    page = <PhonePage navigate={navigate} />;
  } else {
    page = <HomePage navigate={navigate} tweaks={tweaks} />;
  }

  return (
    <>
      {window.__STAGING__ && <div style={{ position: "fixed", top: 0, left: 0, right: 0, zIndex: 9999, background: "#E04E33", color: "#fff", textAlign: "center", padding: "8px 16px", fontSize: 13, fontWeight: 700, fontFamily: "monospace" }}>⚠️ STAGING — Test payments only. Not the live site.</div>}
      <AnnouncementBar navigate={navigate} />
      <Navbar currentRoute={effectivePathOnly} navigate={navigate} />
      <GutterStickers currentRoute={effectivePathOnly} />
      {page}

      <EmailSignup />
      <Footer navigate={navigate} currentRoute={effectivePathOnly} />
      <CookieBanner navigate={navigate} />
      {editOpen && (
        <CiaoTweaks
          tweaks={tweaks}
          updateTweak={updateTweak}
          onClose={() => {
            setEditOpen(false);
            window.parent.postMessage({ type: '__edit_mode_dismissed' }, '*');
          }}
        />
      )}
    </>
  );
}

// ── Tweaks panel ──
function CiaoTweaks({ tweaks, updateTweak, onClose }) {
  return (
    <div style={{
      position: 'fixed', right: 24, bottom: 24, zIndex: 100,
      width: 280,
      background: '#fff',
      border: '1px solid var(--border)',
      borderRadius: 18,
      boxShadow: '0 20px 40px rgba(0,0,0,0.15)',
      fontFamily: 'var(--body)',
      overflow: 'hidden',
    }}>
      <div style={{ padding: '16px 18px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontFamily: 'var(--heading-font)', fontWeight: 500, fontSize: 16, color: 'var(--heading)' }}>Tweaks</span>
        <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', fontSize: 18, color: 'var(--muted)' }}>×</button>
      </div>
      <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div>
          <label style={{ fontSize: 12, fontWeight: 600, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', display: 'block', marginBottom: 8 }}>Hero headline</label>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
            {[
              { id: 'a', label: 'iPhones can wait' },
              { id: 'b', label: 'Made for love' },
              { id: 'c', label: 'Only matters' },
            ].map(o => (
              <button key={o.id} onClick={() => updateTweak('headline', o.id)}
                style={{
                  padding: '8px 6px',
                  borderRadius: 8,
                  border: '1px solid ' + (tweaks.headline === o.id ? 'var(--cta)' : 'var(--border)'),
                  background: tweaks.headline === o.id ? 'var(--cta-circle)' : '#fff',
                  fontSize: 11, fontFamily: 'var(--body)', fontWeight: 500,
                  cursor: 'pointer', textAlign: 'center', lineHeight: 1.3,
                  color: 'var(--heading)',
                }}>{o.label}</button>
            ))}
          </div>
        </div>
        <div style={{ fontFamily: 'var(--hand)', fontSize: 13, color: 'var(--muted)', lineHeight: 1.5, paddingTop: 4, borderTop: '1px dashed var(--border)' }}>
          Tip: navigate using the menu (Home · About · Pre-order) — full restyled brand site.
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { App });

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