/* === Main app ======================================================== */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "lang": "en",
  "direction": "heritage",
  "heroStyle": "video",
  "density": "regular",
  "cardStyle": "bordered",
  "shape": "square",
  "preview": "desktop",
  "animations": "subtle"
}/*EDITMODE-END*/;

/* ----- Visual-direction presets ----- */
/* Four distinct aesthetic systems. Each remaps the core tokens. */
const DIRECTIONS = {
  heritage: {
    label: 'Classic Heritage',
    fontDisplay: "'Cormorant Garamond', serif",
    fontBody:    "'Jost', sans-serif",
    fontMono:    "'JetBrains Mono', monospace",
    displayWeight: 300,
    displayItalic: 'italic',
    accent:       '#B8881F',
    accent2:      '#B86F3D',
    accentDark:   '#D4A437',
    accentDark2:  '#E6C572',
    bg:           '#F8F3EA',
    bg2:          '#F1EADD',
    surface:      '#FFFCF6',
    fg:           '#1A1816',
    eyebrowCase:  'uppercase',
    eyebrowSpace: '0.32em',
    radius:       '0px',
  },
  boutique: {
    label: 'Modern Boutique',
    fontDisplay: "'Fraunces', serif",
    fontBody:    "'Manrope', sans-serif",
    fontMono:    "'JetBrains Mono', monospace",
    displayWeight: 400,
    displayItalic: 'italic',
    accent:       '#7A5A1F',
    accent2:      '#9B6F2C',
    accentDark:   '#D4A437',
    accentDark2:  '#F0CC6E',
    bg:           '#FAF7F1',
    bg2:          '#F3EFE5',
    surface:      '#FFFFFF',
    fg:           '#1F1B14',
    eyebrowCase:  'none',
    eyebrowSpace: '0.04em',
    radius:       '12px',
  },
  editorial: {
    label: 'Editorial Bold',
    fontDisplay: "'DM Serif Display', serif",
    fontBody:    "'Space Grotesk', sans-serif",
    fontMono:    "'JetBrains Mono', monospace",
    displayWeight: 400,
    displayItalic: 'normal',
    accent:       '#1A1816',
    accent2:      '#B8881F',
    accentDark:   '#D4A437',
    accentDark2:  '#E6C572',
    bg:           '#EFEAE0',
    bg2:          '#E5DECF',
    surface:      '#FFFFFF',
    fg:           '#1A1816',
    eyebrowCase:  'uppercase',
    eyebrowSpace: '0.18em',
    radius:       '0px',
  },
  minimal: {
    label: 'Warm Minimal',
    fontDisplay: "'EB Garamond', serif",
    fontBody:    "'Outfit', sans-serif",
    fontMono:    "'JetBrains Mono', monospace",
    displayWeight: 400,
    displayItalic: 'italic',
    accent:       '#8B6A3F',
    accent2:      '#5A4225',
    accentDark:   '#D4A437',
    accentDark2:  '#E6C572',
    bg:           '#FBF8F2',
    bg2:          '#F5F0E4',
    surface:      '#FFFFFF',
    fg:           '#26221C',
    eyebrowCase:  'none',
    eyebrowSpace: '0.08em',
    radius:       '24px',
  },
};

const DENSITIES = {
  cozy:    { sectionPad: 64,  cardPad: 20, heroPad: 80 },
  regular: { sectionPad: 120, cardPad: 28, heroPad: 120 },
  spacious:{ sectionPad: 180, cardPad: 40, heroPad: 160 },
};

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const VALID_PAGES = ['home', 'rooms', 'dining', 'experiences', 'gallery', 'contact'];
  const pageFromHash = () => {
    const hash = window.location.hash.replace('#', '');
    return VALID_PAGES.includes(hash) ? hash : 'home';
  };

  const [page, setPage] = useState(pageFromHash);
  const [bookingOpen, setBookingOpen] = useState(false);
  const lang = tweaks.lang || 'en';
  const theme = tweaks.theme || 'light';

  /* ----- i18n ----- */
  const t = useCallback((key) => {
    const dict = TRANSLATIONS[lang] || TRANSLATIONS.en;
    return dict[key] || TRANSLATIONS.en[key] || key;
  }, [lang]);

  /* Apply theme */
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  /* Apply lang attribute (helps font choice for Devanagari) */
  useEffect(() => {
    document.documentElement.setAttribute('lang', lang === 'ne' ? 'ne' : 'en');
  }, [lang]);

  /* Apply visual-direction tokens */
  useEffect(() => {
    const dir = DIRECTIONS[tweaks.direction] || DIRECTIONS.heritage;
    const root = document.documentElement;
    root.style.setProperty('--font-display', dir.fontDisplay);
    root.style.setProperty('--font-body',    dir.fontBody);
    root.style.setProperty('--font-mono',    dir.fontMono);
    root.style.setProperty('--display-weight', String(dir.displayWeight));
    root.style.setProperty('--display-italic', dir.displayItalic);
    root.style.setProperty('--eyebrow-case',   dir.eyebrowCase);
    root.style.setProperty('--eyebrow-space',  dir.eyebrowSpace);
    root.style.setProperty('--radius',         dir.radius);
    /* Accent depends on theme */
    if (theme === 'dark') {
      root.style.setProperty('--accent',  dir.accentDark);
      root.style.setProperty('--accent-2', dir.accentDark2);
      /* Clear light-mode overrides so [data-theme="dark"] tokens apply */
      root.style.removeProperty('--bg');
      root.style.removeProperty('--bg-2');
      root.style.removeProperty('--surface');
      root.style.removeProperty('--fg');
    } else {
      root.style.setProperty('--accent',  dir.accent);
      root.style.setProperty('--accent-2', dir.accent2);
      root.style.setProperty('--bg',  dir.bg);
      root.style.setProperty('--bg-2', dir.bg2);
      root.style.setProperty('--surface', dir.surface);
      root.style.setProperty('--fg',  dir.fg);
    }
  }, [tweaks.direction, theme]);

  /* Apply density */
  useEffect(() => {
    const d = DENSITIES[tweaks.density] || DENSITIES.regular;
    const root = document.documentElement;
    root.style.setProperty('--section-pad', `${d.sectionPad}px`);
    root.style.setProperty('--card-pad',    `${d.cardPad}px`);
    root.style.setProperty('--hero-pad',    `${d.heroPad}px`);
  }, [tweaks.density]);

  /* Animations toggle */
  useEffect(() => {
    document.documentElement.setAttribute('data-animations', tweaks.animations || 'subtle');
  }, [tweaks.animations]);

  /* Card style + shape */
  useEffect(() => {
    document.documentElement.setAttribute('data-card-style', tweaks.cardStyle || 'bordered');
    document.documentElement.setAttribute('data-shape', tweaks.shape || 'square');
  }, [tweaks.cardStyle, tweaks.shape]);

  /* Sync hash → page on browser back/forward */
  useEffect(() => {
    const onHashChange = () => setPage(pageFromHash());
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, []);

  /* Reset scroll on nav */
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [page]);

  const handleNav = useCallback((id) => {
    if (id === 'booking') { setBookingOpen(true); return; }
    window.location.hash = id === 'home' ? '' : id;
    setPage(id);
  }, []);
  const handleBook = useCallback(() => setBookingOpen(true), []);
  const toggleTheme = useCallback(() => setTweak('theme', theme === 'light' ? 'dark' : 'light'), [theme, setTweak]);
  const changeLang = useCallback((l) => setTweak('lang', l), [setTweak]);

  const i18nValue = useMemo(() => ({ lang, t, setLang: changeLang }), [lang, t, changeLang]);

  /* Mobile preview frame wraps the entire app */
  const isMobilePreview = tweaks.preview === 'mobile';

  const innerApp = (
    <I18nProvider value={i18nValue}>
      <div className="shell">
        <div className="grain" />
        <Nav
          page={page}
          onNav={handleNav}
          theme={theme}
          onToggleTheme={toggleTheme}
          lang={lang}
          onChangeLang={changeLang}
          onBook={handleBook}
        />

        <main key={page}>
          {page === 'home' && <HomeView onBook={handleBook} onNav={handleNav} tweaks={tweaks} />}
          {page === 'rooms' && <RoomsView onBook={handleBook} />}
          {page === 'dining' && <DiningView />}
          {page === 'experiences' && <ExperiencesView />}
          {page === 'gallery' && <GalleryView />}
          {page === 'contact' && <ContactView />}
        </main>

        <Footer onNav={handleNav} onBook={handleBook} />

        <BookingOverlay open={bookingOpen} onClose={() => setBookingOpen(false)} />
      </div>
    </I18nProvider>
  );

  return (
    <>
      {isMobilePreview ? <MobileFrame>{innerApp}</MobileFrame> : innerApp}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Language & Theme">
          <TweakRadio
            label="Language"
            value={tweaks.lang}
            options={[{ value: 'en', label: 'EN' }, { value: 'ne', label: 'नेपाली' }]}
            onChange={v => setTweak('lang', v)}
          />
          <TweakRadio
            label="Theme"
            value={tweaks.theme}
            options={['light', 'dark']}
            onChange={v => setTweak('theme', v)}
          />
        </TweakSection>

        <TweakSection label="Visual Direction">
          <TweakSelect
            label="Aesthetic"
            value={tweaks.direction}
            options={Object.entries(DIRECTIONS).map(([v, d]) => ({ value: v, label: d.label }))}
            onChange={v => setTweak('direction', v)}
          />
          <TweakRadio
            label="Density"
            value={tweaks.density}
            options={['cozy', 'regular', 'spacious']}
            onChange={v => setTweak('density', v)}
          />
          <TweakRadio
            label="Shape"
            value={tweaks.shape}
            options={['square', 'soft', 'round']}
            onChange={v => setTweak('shape', v)}
          />
        </TweakSection>

        <TweakSection label="Hero & Motion">
          <TweakSelect
            label="Hero Background"
            value={tweaks.heroStyle}
            options={[
              { value: 'video', label: 'Property video' },
              { value: 'photo', label: 'Photo' },
              { value: 'metal', label: 'Solid metallic' },
            ]}
            onChange={v => setTweak('heroStyle', v)}
          />
          <TweakRadio
            label="Animations"
            value={tweaks.animations}
            options={['subtle', 'lively']}
            onChange={v => setTweak('animations', v)}
          />
        </TweakSection>

        <TweakSection label="Preview">
          <TweakRadio
            label="Device"
            value={tweaks.preview}
            options={['desktop', 'mobile']}
            onChange={v => setTweak('preview', v)}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

/* ----- Mobile preview frame ----- */
function MobileFrame({ children }) {
  return (
    <div className="mobile-stage">
      <div className="mobile-frame">
        <div className="mobile-notch"/>
        <div className="mobile-screen">
          {children}
        </div>
        <div className="mobile-home"/>
      </div>
    </div>
  );
}

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