// Facette — App shell
// Renders the desktop site + an iPhone-framed mobile mirror

const { useState, useEffect } = React;

function Site({ page, setPage, branch, setBranch, openBook, openQuiz, openLightbox, isMobile }) {
  // Page header sticks
  return (
    <div className={`site ${isMobile ? 'is-mobile' : ''}`}>
      <Header page={page} setPage={setPage} branch={branch} setBranch={setBranch}
              openBook={openBook} isMobile={isMobile} />
      {page === 'home' && (
        <Home branch={branch} setBranch={setBranch}
              openBook={openBook} openQuiz={openQuiz} openLightbox={openLightbox}
              setPage={setPage} isMobile={isMobile} />
      )}
      {page === 'treatments' && (
        <Treatments branch={branch} openBook={openBook} isMobile={isMobile} />
      )}
      {page === 'memberships' && (
        <Memberships branch={branch} openBook={openBook} setPage={setPage} isMobile={isMobile} />
      )}
      {page === 'locations' && (
        <Locations branch={branch} setBranch={setBranch} openBook={openBook} isMobile={isMobile} />
      )}
      <Footer setPage={setPage} branch={branch} setBranch={setBranch} />
      {isMobile && <MobileBottomBar branch={branch} openBook={openBook} />}
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Stage chrome — top bar over both viewports
// ──────────────────────────────────────────────────────────
function StageChrome({ branch, setBranch, mobileVisible, setMobileVisible, palette, setPalette, openTweaks }) {
  return (
    <div className="stage-chrome">
      <div className="sc-brand">
        <span className="sc-dot"></span>
        <span>Facette · Hi-fi prototype</span>
      </div>
      <div className="sc-controls">
        <span className="sc-lab">BRANCH</span>
        <button
          className={`sc-btn ${branch === 'jumeirah' ? 'active' : ''}`}
          onClick={() => setBranch('jumeirah')}>Jumeirah</button>
        <button
          className={`sc-btn ${branch === 'business_bay' ? 'active' : ''}`}
          onClick={() => setBranch('business_bay')}>Business Bay</button>
        <div className="sc-divider"></div>
        <span className="sc-lab">VIEW</span>
        <button
          className={`sc-btn ${mobileVisible ? 'active' : ''}`}
          onClick={() => setMobileVisible(!mobileVisible)}>
          {mobileVisible ? 'Hide mobile' : 'Show mobile'}
        </button>
        <div className="sc-divider"></div>
        <button className="sc-btn" onClick={openTweaks}>Tweaks</button>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Mobile shell — wraps the Site in an iPhone frame
// ──────────────────────────────────────────────────────────
function MobileShell(props) {
  return (
    <div className="mobile-shell">
      <IOSDevice width={398} height={830} dark={false} keyboard={false}>
        <div className="ios-scroll" style={{
          width: '100%', height: '100%',
          overflowY: 'auto',
          overflowX: 'hidden',
          position: 'relative',
        }}>
          <Site {...props} isMobile={true} />
        </div>
      </IOSDevice>
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// App
// ──────────────────────────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "luminous",
  "heroLayout": "split",
  "mobileVisible": true,
  "showFlyout": true
}/*EDITMODE-END*/;

function App() {
  const initialPage = window.__BYTESGLUE_SHOWCASE_ROUTE || 'home';
  const [page, setPage] = useState(initialPage);
  const [branch, setBranch] = useState('jumeirah');
  const [bookOpen, setBookOpen] = useState(false);
  const [bookTreatment, setBookTreatment] = useState(null);
  const [quizOpen, setQuizOpen] = useState(false);
  const [lightboxSrc, setLightboxSrc] = useState(null);
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const openTweaks = () => {
    window.postMessage({ type: '__activate_edit_mode' }, '*');
  };

  // Apply palette to root
  useEffect(() => {
    document.documentElement.setAttribute('data-palette', tweaks.palette);
  }, [tweaks.palette]);

  // Reset page scroll when changing page (within each scroll container)
  useEffect(() => {
    document.querySelectorAll('.stage-desktop, .ios-scroll').forEach((el) => {
      el.scrollTo({ top: 0, behavior: 'smooth' });
    });
  }, [page]);

  // Sticky book CTA visibility tied to desktop scroll
  const [showSticky, setShowSticky] = useState(false);
  useEffect(() => {
    const el = document.querySelector('.stage-desktop');
    if (!el) return;
    const handler = () => setShowSticky(el.scrollTop > 600);
    el.addEventListener('scroll', handler);
    return () => el.removeEventListener('scroll', handler);
  }, []);

  // Scale-to-fit: stage has a fixed design width; we scale it to viewport.
  useEffect(() => {
    const DESIGN_W = tweaks.mobileVisible ? 1680 : 1280;
    const CHROME_H = 52;
    const update = () => {
      const vw = window.innerWidth;
      const vh = window.innerHeight - CHROME_H;
      const scale = Math.min(1, vw / DESIGN_W);
      document.documentElement.style.setProperty('--stage-scale', scale);
      document.documentElement.style.setProperty('--stage-w', DESIGN_W + 'px');
      document.documentElement.style.setProperty('--stage-h', (vh / scale) + 'px');
    };
    update();
    window.addEventListener('resize', update);
    return () => window.removeEventListener('resize', update);
  }, [tweaks.mobileVisible]);

  const openBook = (treatment) => {
    setBookTreatment(treatment || null);
    setBookOpen(true);
  };
  const openQuiz = () => setQuizOpen(true);
  const openLightbox = (src) => setLightboxSrc(src);

  const siteProps = {
    page, setPage, branch, setBranch,
    openBook, openQuiz, openLightbox,
  };

  return (
    <React.Fragment>
      <StageChrome
        branch={branch} setBranch={setBranch}
        mobileVisible={tweaks.mobileVisible}
        setMobileVisible={(v) => setTweak('mobileVisible', v)}
        palette={tweaks.palette}
        setPalette={(p) => setTweak('palette', p)}
        openTweaks={openTweaks}
      />
      <div className="stage-wrap">
        <div className={`stage ${!tweaks.mobileVisible ? 'mobile-hidden' : ''}`}>
          <div className="stage-desktop">
            <Site {...siteProps} isMobile={false} />
            {tweaks.showFlyout && (
              <Flyout
                openBook={openBook}
                showSticky={showSticky && !bookOpen && !quizOpen}
                stickyTreatment={page === 'home' ? null : null}
              />
            )}
          </div>
          {tweaks.mobileVisible && (
            <div className="stage-mobile">
              <MobileShell {...siteProps} />
            </div>
          )}
        </div>
      </div>

      {/* Modals */}
      {bookOpen && (
        <BookModal
          branch={branch}
          treatment={bookTreatment}
          onClose={() => setBookOpen(false)}
          onBranchChange={setBranch}
        />
      )}
      {quizOpen && (
        <QuizModal
          onClose={() => setQuizOpen(false)}
          onBook={(treatment) => {
            setQuizOpen(false);
            openBook(treatment);
          }}
        />
      )}
      {lightboxSrc && (
        <Lightbox src={lightboxSrc} onClose={() => setLightboxSrc(null)} />
      )}

      {/* Tweaks panel — self-manages open state */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Palette">
          <TweakRadio
            label="Mood"
            value={tweaks.palette}
            onChange={(v) => setTweak('palette', v)}
            options={[
              { value: 'luminous', label: 'Luminous' },
              { value: 'clinical', label: 'Clinical' },
              { value: 'boutique', label: 'Boutique' },
            ]}
          />
        </TweakSection>
        <TweakSection label="Stage">
          <TweakToggle
            label="Mobile preview"
            value={tweaks.mobileVisible}
            onChange={(v) => setTweak('mobileVisible', v)}
          />
          <TweakToggle
            label="WhatsApp flyout"
            value={tweaks.showFlyout}
            onChange={(v) => setTweak('showFlyout', v)}
          />
        </TweakSection>
        <TweakSection label="Active branch">
          <TweakRadio
            label="Branch"
            value={branch}
            onChange={setBranch}
            options={[
              { value: 'jumeirah', label: 'Jumeirah' },
              { value: 'business_bay', label: 'Business Bay' },
            ]}
          />
        </TweakSection>
        <TweakSection label="Quick demos">
          <TweakButton label="Open Book flow →" onClick={() => openBook()} />
          <TweakButton label="Open Skin Quiz →" onClick={() => setQuizOpen(true)} />
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

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