/* ---- Tweak helpers: derive a full accent ramp + atmosphere/texture presets ---- */
function _hexRgb(h) { h = h.replace('#', ''); return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)]; }
function _mix(rgb, target, amt) { return rgb.map((c, i) => Math.round(c + (target[i] - c) * amt)); }
function _rgba(rgb, a) { return `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${a})`; }
function _hex(rgb) { return '#' + rgb.map((c) => c.toString(16).padStart(2, '0')).join(''); }
function accentVars(hex) {
  const rgb = _hexRgb(hex);
  const hover = _hex(_mix(rgb, [255, 255, 255], 0.26));
  const press = _hex(_mix(rgb, [0, 0, 0], 0.18));
  const arctic = _hex(_mix(rgb, [255, 255, 255], 0.4));
  return {
    '--accent': hex,
    '--accent-hover': hover,
    '--accent-press': press,
    '--arctic-blue': arctic,
    '--accent-soft': _rgba(rgb, 0.14),
    '--accent-line': _rgba(rgb, 0.3),
    '--border-accent': _rgba(rgb, 0.45),
    '--gradient-accent': `linear-gradient(135deg, ${hover} 0%, ${hex} 60%, ${press} 100%)`,
    '--gradient-hero': `radial-gradient(120% 120% at 80% 0%, ${_rgba(rgb, 0.34)} 0%, rgba(43,62,122,0.20) 32%, rgba(22,22,26,0) 62%), #16161A`,
    '--glow-accent': `0 8px 30px -6px ${_rgba(rgb, 0.45)}`,
  };
}
const ATMOSPHERE = {
  cool: 'linear-gradient(160deg, #16161A 0%, #1C2748 62%, #2B3E7A 100%)',
  balanced: 'linear-gradient(160deg, #16161A 0%, #23233C 55%, #3C3656 100%)',
  warm: 'linear-gradient(160deg, #16161A 0%, #2A1E2A 52%, #5E3B33 100%)',
};
const TEXTURE = { off: 'rgba(0,0,0,0)', subtle: 'rgba(232,236,247,0.045)', bold: 'rgba(232,236,247,0.11)' };

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#6886FC",
  "atmosphere": "cool",
  "texture": "subtle"
}/*EDITMODE-END*/;

function App() {
  const { useTweaks, TweaksPanel, TweakSection, TweakColor, TweakRadio } = window;
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [site, setSite] = React.useState(window.EPCM_INITIAL_SITE || 'hvac');
  const [page, setPage] = React.useState(window.EPCM_INITIAL_PAGE || 'home');
  const [lang, setLang] = React.useState(window.EPCM_INITIAL_LANG || 'en');
  const [booking, setBooking] = React.useState(false);
  const [quote, setQuote] = React.useState(false);
  const scroller = React.useRef(null);

  // Static city pages link here with ?soumission=1 / ?quote=1 to open the quote form.
  React.useEffect(() => {
    const q = new URLSearchParams(window.location.search);
    if (q.has('soumission') || q.has('quote')) setQuote(true);
  }, []);

  const toTop = () => requestAnimationFrame(() => { if (scroller.current) scroller.current.scrollTop = 0; window.scrollTo({ top: 0 }); });
  const pushUrl = (id) => {
    try {
      const map = (lang === 'en' ? (window.EPCM_URLS_EN || {}) : (window.EPCM_URLS || {}));
      const P2 = window.EPCM_PAGES || {};
      const url = map[id] || (P2[id] && P2[id].path) || (id === 'home' ? '/' : null);
      const full = lang === 'en' && url && url.indexOf('/en/') !== 0 ? url : url;
      if (full && window.location.pathname !== full) window.history.pushState({ page: id }, '', full);
    } catch (e) {}
  };
  const navigate = (p) => { setPage(p || 'home'); pushUrl(p || 'home'); toTop(); };
  const navigatePlumbing = (id) => { setPage(id === 'home' ? 'plumbing-home' : id); toTop(); };
  const goPlumbing = () => { setSite('plumbing'); setPage('plumbing-home'); toTop(); };
  const backHvac = () => { setSite('hvac'); setPage('home'); toTop(); };
  const openBook = () => setBooking(true);
  const openQuote = () => setQuote(true);
  // Switch language in place (no reload) and keep the URL in sync — a hard
  // navigation here produced a blank page when the target file wasn't served.
  const toggleLang = () => {
    const next = lang === 'en' ? 'fr' : 'en';
    setLang(next);
    try {
      const map = next === 'en' ? (window.EPCM_URLS_EN || {}) : (window.EPCM_URLS || {});
      const url = map[page] || (next === 'en' ? '/en/' : '/');
      if (url && window.location.pathname !== url) window.history.pushState({ page, lang: next }, '', url);
    } catch (e) {}
    toTop();
  };

  // Per-route SEO: title, meta description, canonical + html lang
  React.useEffect(() => {
    const P = window.EPCM_PAGES || {};
    const pick = (t) => (!t ? '' : (typeof t === 'string' ? t : (t[lang] || t.fr || t.en || '')));
    const setMeta = (sel, attrName, val) => {
      if (!val) return;
      let el = document.head.querySelector(sel);
      if (!el) {
        el = document.createElement(sel.startsWith('link') ? 'link' : 'meta');
        if (sel.includes('property=')) el.setAttribute('property', sel.match(/property="([^"]+)"/)[1]);
        else if (sel.includes('name=')) el.setAttribute('name', sel.match(/name="([^"]+)"/)[1]);
        else if (sel.startsWith('link')) el.setAttribute('rel', 'canonical');
        document.head.appendChild(el);
      }
      el.setAttribute(attrName, val);
    };

    const BRAND = 'EPCM';
    const DOMAIN = 'https://electro-pompe.com';
    let title, desc, path;

    if (page === 'home' || page === 'plumbing-home') {
      const plumb = page === 'plumbing-home';
      title = plumb
        ? (lang === 'fr' ? `Plomberie à Montréal et Laval | ${BRAND}` : `Plumbing in Montreal & Laval | ${BRAND}`)
        : (lang === 'fr' ? `Chauffage, Climatisation & Thermopompes à Montréal | ${BRAND}` : `Heating, Cooling & Heat Pumps in Montreal | ${BRAND}`);
      desc = plumb
        ? (lang === 'fr' ? 'Plombiers licenciés et assurés à Montréal et Laval : chauffe-eau, débouchage, fuites et urgences. Depuis 1982. ☎ (450) 328-1110' : 'Licensed, insured plumbers in Montreal & Laval: water heaters, drains, leaks and emergencies. Since 1982. ☎ (450) 328-1110')
        : (lang === 'fr' ? 'EPCM — chauffage, climatisation et thermopompes à Montréal et Laval depuis 1982. Installation, réparation, entretien. Certifié RBQ. ☎ (450) 328-1110' : 'EPCM — heating, cooling and heat pumps in Montreal & Laval since 1982. Installation, repair, maintenance. RBQ-licensed. ☎ (450) 328-1110');
      path = window.EPCM_PATH_OVERRIDE && page === (window.EPCM_INITIAL_PAGE || 'home') ? window.EPCM_PATH_OVERRIDE : (plumb ? '/plumbing-services-montreal-laval/' : '/');
    } else {
      const p = P[page];
      title = (p && pick(p.meta && p.meta.title)) || (p ? `${pick(p.h1)} | ${BRAND}` : `${BRAND} — Chauffage & Climatisation`);
      desc = (p && pick(p.meta && p.meta.description)) || (p ? pick(p.intro).slice(0, 155) : '');
      path = (window.EPCM_PATH_OVERRIDE && page === (window.EPCM_INITIAL_PAGE || 'home') ? window.EPCM_PATH_OVERRIDE : ((p && p.path) || '/'));
    }

    document.title = title;
    document.documentElement.lang = lang === 'fr' ? 'fr-CA' : 'en-CA';
    setMeta('meta[name="description"]', 'content', desc);
    setMeta('link[rel="canonical"]', 'href', DOMAIN + path);
    setMeta('meta[property="og:title"]', 'content', title);
    setMeta('meta[property="og:description"]', 'content', desc);
    setMeta('meta[property="og:url"]', 'content', DOMAIN + path);
    setMeta('meta[property="og:image"]', 'content', DOMAIN + '/assets/og-cover.jpg');
    setMeta('meta[property="og:locale"]', 'content', lang === 'fr' ? 'fr_CA' : 'en_CA');
    setMeta('meta[name="twitter:card"]', 'content', 'summary_large_image');
    setMeta('meta[name="twitter:title"]', 'content', title);
    setMeta('meta[name="twitter:description"]', 'content', desc);
  }, [page, site, lang]);

  let body;
  if (site === 'plumbing') {
    body = <window.PlumbingSite lang={lang} page={page} onNavigate={navigatePlumbing} onBook={openBook} onBackHvac={backHvac} onLang={toggleLang} />;
  } else {
    const view = page === 'home'
      ? <window.Home lang={lang} onNavigate={navigate} onBook={openBook} onQuote={openQuote} />
      : <window.PageView id={page} lang={lang} onNavigate={navigate} onBook={openBook} onQuote={openQuote} />;
    body = (
      <React.Fragment>
        <window.AnnouncementBar lang={lang} onNavigate={navigate} />
        <window.Header onNavigate={navigate} onBook={openBook} onGoPlumbing={goPlumbing} page={page} lang={lang} onLang={toggleLang} />
        {view}
        <window.Footer onNavigate={navigate} onBook={openBook} onQuote={openQuote} lang={lang} />
      </React.Fragment>
    );
  }

  // Tweaks only reshape the HVAC site; the plumbing sub-site keeps its own theme.
  const tweakVars = site === 'plumbing' ? {} : { ...accentVars(tw.accent), '--gradient-environment': ATMOSPHERE[tw.atmosphere] || ATMOSPHERE.cool, '--grid-line': TEXTURE[tw.texture] || TEXTURE.subtle };

  return (
    <div ref={scroller} className={site === 'plumbing' ? 'epcm-plumbing-theme' : ''} style={{ minHeight: '100%', background: 'var(--bg)', ...tweakVars }} lang={lang}>
      {body}
      <window.BookingModal open={booking} onClose={() => setBooking(false)} lang={lang} />
      <window.QuoteModal open={quote} onClose={() => setQuote(false)} lang={lang} />
      <TweaksPanel title="Tweaks">
        <TweakSection label="Brand accent" />
        <TweakColor label="Accent" value={tw.accent} options={['#6886FC', '#22C7DB', '#E8843C', '#7A5AE0']} onChange={(v) => setTweak('accent', v)} />
        <TweakSection label="Atmosphere" />
        <TweakRadio label="Temperature" value={tw.atmosphere} options={['cool', 'balanced', 'warm']} onChange={(v) => setTweak('atmosphere', v)} />
        <TweakSection label="Texture" />
        <TweakRadio label="Blueprint grid" value={tw.texture} options={['off', 'subtle', 'bold']} onChange={(v) => setTweak('texture', v)} />
      </TweaksPanel>
    </div>
  );
}

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