/* global React, ReactDOM, Icon, CustomCursor, Nav, HomePage, ServicesPage, RentalsPage, AboutPage, JournalPage, ContactPage, PrivacyPage,
   TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakToggle, WORK, slugForWork */
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "reel",
  "customCursor": false,
  "waveDividers": false
}/*EDITMODE-END*/;

const PAGES = ['home', 'services', 'rentals', 'about', 'journal', 'contact', 'privacy'];
const RENTALS_SUB_PAGES = ['equipment', 'contact', 'open-account'];

// Path-based routing. Productions live at /work/:slug and are rendered as a
// modal over the home page, so { page: 'home', workSlug: '...' } is a valid
// state. Rentals has nested sub-routes /rentals/<sub> for equipment, faqs,
// contact, open-account — these set { page: 'rentals', rentalsSection: '...' }.
const parseLocation = () => {
  const path = (window.location.pathname || '/').replace(/\/+$/, '') || '/';
  if (path === '/') return { page: 'home', workSlug: null, rentalsSection: null };
  const m = path.match(/^\/work\/([^/]+)$/);
  if (m) return { page: 'home', workSlug: m[1], rentalsSection: null };
  const r = path.match(/^\/rentals\/([^/]+)$/);
  if (r) {
    // Known sub-page → render it; unknown sub-page (eg. legacy /rentals/faqs)
    // → fall back to the rentals landing rather than the films home.
    const sub = RENTALS_SUB_PAGES.includes(r[1]) ? r[1] : null;
    return { page: 'rentals', rentalsSection: sub, workSlug: null };
  }
  const seg = path.replace(/^\//, '');
  if (PAGES.includes(seg)) return { page: seg, workSlug: null, rentalsSection: null };
  return { page: 'home', workSlug: null, rentalsSection: null };
};

const PAGE_META = {
  home:     { title: 'Valley Films — Detail driven works for brands & agencies', desc: 'Boutique production company in Acton, West London. Commercials, brand videos, social content and live events — high-budget craft delivered by a small, senior team.' },
  services: { title: 'Services — Valley Films', desc: 'Commercials, brand videos, social content and live events. Four ways we help brands and agencies tell their story.' },
  about:    { title: 'About — Valley Films', desc: 'A small team obsessive about the craft. Founded in 2018, Valley Films is built on the conviction that commercial work deserves the same rigour as documentary.' },
  rentals:  { title: 'Valley Rentals — Studio kit, ready when you are', desc: 'Cinema cameras, prime lenses, lighting, grip and audio kit for hire from our Acton, West London studio. Hand-checked, prep included.' },
  'rentals/equipment':    { title: 'Equipment — Valley Rentals',    desc: 'Browse the live rental shelf. Cameras, lenses, lighting, grip, audio and packages — book by date.' },
  'rentals/contact':      { title: 'Contact — Valley Rentals',      desc: 'Tell us your shoot dates and a kit list. We respond same business day.' },
  'rentals/open-account': { title: 'Open Account — Valley Rentals', desc: 'Open a Valley Rentals account once and skip verification on every future booking. Five minutes to apply.' },
  journal:  { title: 'Journal — Valley Films', desc: 'Field notes, craft pieces and process writing from the Valley Films studio.' },
  contact:  { title: 'Contact — Valley Films', desc: 'Tell us about your project. We respond within one business day with thoughts, references and an honest sense of fit.' },
  privacy:  { title: 'Privacy — Valley Films', desc: 'Privacy notice for valley.film — what we collect, what we don\'t, and how to reach us.' },
};

const ORIGIN = 'https://valley.film';

const pathFor = (loc) => {
  if (loc.workSlug) return `/work/${loc.workSlug}`;
  if (loc.page === 'rentals' && loc.rentalsSection) return `/rentals/${loc.rentalsSection}`;
  return loc.page === 'home' ? '/' : `/${loc.page}`;
};

const setMeta = (loc) => {
  let title, desc;
  if (loc.workSlug && Array.isArray(WORK)) {
    const w = WORK.find((x) => slugForWork(x) === loc.workSlug);
    if (w) {
      title = `${w.title} — ${w.client} · Valley Films`;
      desc = w.description || `${w.client} — ${w.title}. Made by Valley Films.`;
    }
  }
  if (!title) {
    const key = (loc.page === 'rentals' && loc.rentalsSection)
      ? `rentals/${loc.rentalsSection}`
      : loc.page;
    const m = PAGE_META[key] || PAGE_META[loc.page] || PAGE_META.home;
    title = m.title;
    desc = m.desc;
  }
  if (typeof document !== 'undefined') {
    document.title = title;
    const setTag = (selector, attr, value) => {
      const el = document.querySelector(selector);
      if (el) el.setAttribute(attr, value);
    };
    const url = ORIGIN + pathFor(loc);
    setTag('meta[name="description"]', 'content', desc);
    setTag('meta[property="og:title"]', 'content', title);
    setTag('meta[property="og:description"]', 'content', desc);
    setTag('meta[name="twitter:title"]', 'content', title);
    setTag('meta[name="twitter:description"]', 'content', desc);
    setTag('link[rel="canonical"]', 'href', url);
    setTag('meta[property="og:url"]', 'content', url);
  }
};

// Tweaks panel is a dev/design tool — only render in localhost or with ?tweaks=1.
const isTweaksEnabled = () => {
  if (typeof window === 'undefined') return false;
  const host = window.location.hostname;
  if (host === 'localhost' || host === '127.0.0.1' || host.endsWith('.local')) return true;
  return /[?&]tweaks=1\b/.test(window.location.search);
};

function App() {
  const [loc, setLoc] = useState(parseLocation);
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const tweaksEnabled = isTweaksEnabled();
  const { page, workSlug, rentalsSection } = loc;

  // Imperative navigation. Accepts a page name ('about'), a path ('/about'),
  // or a work path ('/work/the-good-fight'). Anchor `<a href="/x">` clicks
  // are handled separately by the click delegate below.
  const goto = (target) => {
    const url = target === 'home'
      ? '/'
      : target.startsWith('/') ? target : `/${target}`;
    if (window.location.pathname === url) {
      window.scrollTo({ top: 0, behavior: 'instant' });
      return;
    }
    window.history.pushState(null, '', url);
    setLoc(parseLocation());
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  // Browser back/forward, plus our own pushState calls when we manually
  // dispatch popstate (we don't, but keeping it general).
  useEffect(() => {
    const onPop = () => {
      setLoc(parseLocation());
      document.body.style.overflow = '';
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  // Migrate legacy hash URLs (#/about) → clean paths (/about) on first paint
  // so old shared links and bookmarks still land correctly.
  useEffect(() => {
    const m = window.location.hash.match(/^#\/?(.+)$/);
    if (m && m[1]) {
      window.history.replaceState(null, '', '/' + m[1]);
      setLoc(parseLocation());
    }
  }, []);

  // Global click delegate: any internal `<a href="/...">` click navigates
  // via pushState instead of a full reload. Modifier keys, target=_blank,
  // mailto:, http://, and protocol-relative URLs all pass through.
  useEffect(() => {
    const onClick = (e) => {
      if (e.defaultPrevented || e.button !== 0) return;
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
      const a = e.target.closest && e.target.closest('a');
      if (!a) return;
      if (a.target && a.target !== '' && a.target !== '_self') return;
      const href = a.getAttribute('href');
      if (!href || !href.startsWith('/') || href.startsWith('//')) return;
      e.preventDefault();
      goto(href);
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
    // goto is stable enough — re-binding every render is cheap and avoids
    // stale closures pointing at an old setLoc.
  });

  useEffect(() => {
    document.body.classList.toggle('has-custom-cursor', !!tweaks.customCursor);
  }, [tweaks.customCursor]);

  useEffect(() => {
    document.body.classList.toggle('has-wave-dividers', !!tweaks.waveDividers);
  }, [tweaks.waveDividers]);

  useEffect(() => {
    document.body.classList.toggle('is-rentals-page', page === 'rentals');
  }, [page]);

  useEffect(() => {
    setMeta(loc);
  }, [page, workSlug, rentalsSection]);

  let Page = HomePage;
  if (page === 'services') Page = ServicesPage;
  if (page === 'rentals')  Page = RentalsPage;
  if (page === 'about')    Page = AboutPage;
  if (page === 'journal')  Page = JournalPage;
  if (page === 'contact')  Page = ContactPage;
  if (page === 'privacy')  Page = PrivacyPage;

  return (
    <React.Fragment>
      {tweaks.customCursor && <CustomCursor/>}
      <Nav page={page} isRentals={page === 'rentals'} rentalsSection={rentalsSection}/>
      <Page onGoto={goto} heroVariant={tweaks.heroVariant} workSlug={workSlug} rentalsSection={rentalsSection}/>

      {tweaksEnabled && (
        <TweaksPanel>
          <TweakSection label="Hero variant"/>
          <TweakRadio
            label="Opening"
            value={tweaks.heroVariant}
            options={[
              { value: 'marquee', label: 'Marquee' },
              { value: 'stacked', label: 'Stacked' },
              { value: 'reel',    label: 'Reel' },
            ]}
            onChange={(v) => setTweak('heroVariant', v)}
          />
          <TweakSection label="Interaction"/>
          <TweakToggle
            label="Custom cursor"
            value={!!tweaks.customCursor}
            onChange={(v) => setTweak('customCursor', v)}
          />
          <TweakToggle
            label="Wave dividers"
            value={!!tweaks.waveDividers}
            onChange={(v) => setTweak('waveDividers', v)}
          />
        </TweaksPanel>
      )}
    </React.Fragment>
  );
}

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