// Main app — composes the page and wires Tweaks panel.

const { Header, Hero, ServicesSection, CasesSection, ProcessSection, PainSection, FAQSection, FinalCTA, Footer } = window.Sections;
const { ChatBody, FloatingChat } = window.Chat;

// Tweak defaults are persisted by the host: anything between the markers
// below gets rewritten when tweaks are saved.
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "dark",
  "accent": "indigo-pink-amber",
  "accentSwatch": 0,
  "headingFont": "JetBrains Mono",
  "density": "comfortable",
  "heroIntensity": 100,
  "viewportMode": "single",
  "brand": "thevoyd",
  "brandDisplay": "THEVOYD",
  "chatAutoOpen": true,
  "lang": "ru"
}/*EDITMODE-END*/;

const ACCENT_PALETTES = {
  'indigo-pink-amber': { acc1: '#6366f1', acc2: '#ec4899', acc3: '#f59e0b' },
  'electric-blue':     { acc1: '#3b82f6', acc2: '#60a5fa', acc3: '#a78bfa' },
  'acid-green':        { acc1: '#4ade80', acc2: '#22d3ee', acc3: '#f5f5f4' },
  'mono':              { acc1: '#fafaf7', acc2: '#fafaf7', acc3: '#fafaf7' },
};

const ACCENT_SWATCH_LIST = ['indigo-pink-amber','electric-blue','acid-green','mono'];

const FONT_MAP = {
  'JetBrains Mono':   "'JetBrains Mono', ui-monospace, monospace",
  'Inter Tight':      "'Inter Tight', 'Inter', system-ui, sans-serif",
  'Instrument Serif': "'Instrument Serif', 'Inter Tight', Georgia, serif",
};

function applyTweaksToDOM(tw) {
  const root = document.documentElement;
  const pal = ACCENT_PALETTES[ACCENT_SWATCH_LIST[tw.accentSwatch] || tw.accent] || ACCENT_PALETTES['indigo-pink-amber'];
  root.style.setProperty('--acc-1', pal.acc1);
  root.style.setProperty('--acc-2', pal.acc2);
  root.style.setProperty('--acc-3', pal.acc3);
  root.style.setProperty('--gradient', `linear-gradient(135deg, ${pal.acc1} 0%, ${pal.acc2} 50%, ${pal.acc3} 100%)`);
  root.style.setProperty('--font-head', FONT_MAP[tw.headingFont] || FONT_MAP['JetBrains Mono']);
  root.style.setProperty('--density', tw.density === 'tight' ? '0.78' : '1');
  if (tw.palette === 'paper') {
    root.style.setProperty('--bg', '#f4f1ea');
    root.style.setProperty('--bg-elev', '#ffffff');
    root.style.setProperty('--fg', '#0a0a0a');
    root.style.setProperty('--fg-dim', 'rgba(10,10,10,0.62)');
    root.style.setProperty('--muted', 'rgba(10,10,10,0.42)');
    root.style.setProperty('--line', 'rgba(10,10,10,0.10)');
    root.style.setProperty('--line-strong', 'rgba(10,10,10,0.22)');
  } else {
    root.style.setProperty('--bg', '#0a0a0a');
    root.style.setProperty('--bg-elev', '#111111');
    root.style.setProperty('--fg', '#fafaf7');
    root.style.setProperty('--fg-dim', 'rgba(250,250,247,0.62)');
    root.style.setProperty('--muted', 'rgba(250,250,247,0.42)');
    root.style.setProperty('--line', 'rgba(250,250,247,0.10)');
    root.style.setProperty('--line-strong', 'rgba(250,250,247,0.22)');
  }
}

function MainSite({ tweaks, lang, setLang }) {
  const t = window.DICT[lang];
  const [chatOpen, setChatOpen] = React.useState(() => {
    if (typeof window === 'undefined') return false;
    // open by default on desktop; closed on narrow screens (would cover content)
    return tweaks.chatAutoOpen !== false && window.innerWidth >= 1024;
  });
  const [chatProps, setChatProps] = React.useState({ prefill: null, scenarioHint: null });
  const lastPrefill = React.useRef(0);

  const openChat = React.useCallback((opts = {}) => {
    lastPrefill.current += 1;
    setChatProps({
      prefill: opts.prefill ? opts.prefill + '\u200B'.repeat(lastPrefill.current) : null,
      // strip ZWSPs before sending — added just to force prop change
      scenarioHint: opts.scenarioHint || null,
    });
    setChatOpen(true);
  }, []);

  // Strip the zwsp helper inside chat by passing clean text via key
  const cleanPrefill = chatProps.prefill ? chatProps.prefill.replace(/\u200B/g, '') : null;

  const InlineChat = React.useCallback(({ inline }) => (
    <ChatBody t={t} lang={lang} />
  ), [t, lang]);

  const intensity = (tweaks.heroIntensity ?? 100) / 100;

  return (
    <>
      <Header lang={lang} setLang={setLang} t={t} openChat={() => openChat()} />
      <Hero t={t} brand={tweaks.brand || t.brand} brandDisplay={tweaks.brandDisplay || t.brand_display || (tweaks.brand || t.brand).toUpperCase()} openChat={() => openChat()} heroIntensity={intensity} />
      <ServicesSection t={t} openChat={openChat} />
      <CasesSection t={t} />
      <ProcessSection t={t} />
      <PainSection t={t} openChat={openChat} />
      <FAQSection t={t} />
      <FinalCTA t={t} ChatEmbed={InlineChat} />
      <Footer t={t} />
      <FloatingChat
        t={t}
        lang={lang}
        isOpen={chatOpen}
        setOpen={setChatOpen}
        chatProps={{ prefill: cleanPrefill, scenarioHint: chatProps.scenarioHint }}
      />
    </>
  );
}

function App() {
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [lang, setLangState] = React.useState(() => {
    try { return localStorage.getItem('stdio-lang') || tweaks.lang || 'ru'; }
    catch { return 'ru'; }
  });
  const setLang = (l) => { setLangState(l); try { localStorage.setItem('stdio-lang', l); } catch {} };

  React.useEffect(() => {
    applyTweaksToDOM(tweaks);
  }, [tweaks]);

  return (
    <>
      {tweaks.viewportMode === 'compare' ? (
        <CompareView tweaks={tweaks} lang={lang} setLang={setLang} />
      ) : (
        <MainSite tweaks={tweaks} lang={lang} setLang={setLang} />
      )}
      <TweaksUI tweaks={tweaks} setTweak={setTweak} lang={lang} setLang={setLang} />
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// Compare view: desktop + mobile side by side via scaled clones
// ─────────────────────────────────────────────────────────────
function CompareView({ tweaks, lang, setLang }) {
  // Render two iframes loading this same page in ?embed=1 mode at desktop / mobile widths.
  const url = (w) => `?embed=1&lang=${lang}&w=${w}&accent=${tweaks.accentSwatch}&palette=${tweaks.palette}&density=${tweaks.density}&heroIntensity=${tweaks.heroIntensity}`;
  return (
    <div style={{
      background: '#1a1a1a',
      minHeight: '100vh',
      padding: '80px 40px 40px',
      display: 'grid',
      gridTemplateColumns: '1fr 410px',
      gap: 40,
      alignItems: 'start',
      fontFamily: 'var(--font-body)',
    }}>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14, color: 'rgba(250,250,247,0.55)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase' }}>
          <span>Desktop · 1440</span>
        </div>
        <div style={{
          width: '100%', height: 'calc(100vh - 160px)',
          borderRadius: 8, overflow: 'hidden',
          border: '1px solid rgba(250,250,247,0.18)',
          background: '#0a0a0a',
        }}>
          <iframe src={url(1440)} style={{ width: '100%', height: '100%', border: 0 }} title="Desktop preview"/>
        </div>
      </div>
      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14, color: 'rgba(250,250,247,0.55)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase' }}>
          <span>iPhone · 390</span>
        </div>
        <IOSWrap>
          <iframe src={url(390)} style={{ width: 390, height: '100%', border: 0, background: '#0a0a0a' }} title="Mobile preview"/>
        </IOSWrap>
      </div>
    </div>
  );
}

function IOSWrap({ children }) {
  // Lightweight iOS frame: bezel + status bar + home indicator
  return (
    <div style={{
      width: 410, height: 'calc(100vh - 160px)', minHeight: 720,
      borderRadius: 50, background: '#0a0a0a',
      border: '8px solid #111', padding: 8,
      boxShadow: '0 30px 80px rgba(0,0,0,0.5), inset 0 0 0 1px rgba(250,250,247,0.08)',
      position: 'relative', overflow: 'hidden',
    }}>
      {/* Dynamic island */}
      <div style={{
        position: 'absolute', top: 16, left: '50%', transform: 'translateX(-50%)',
        width: 110, height: 32, borderRadius: 18, background: '#000', zIndex: 2,
      }}/>
      <div style={{ width: '100%', height: '100%', borderRadius: 42, overflow: 'hidden', position: 'relative', background: '#0a0a0a' }}>
        {children}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Tweaks UI
// ─────────────────────────────────────────────────────────────
function TweaksUI({ tweaks, setTweak, lang, setLang }) {
  const { TweaksPanel, TweakSection, TweakRadio, TweakSelect, TweakSlider, TweakText } = window;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Brand" />
      <TweakText label="Name"
        value={tweaks.brand}
        onChange={(v) => setTweak('brand', v)}/>
      <TweakText label="Hero wordmark"
        value={tweaks.brandDisplay}
        onChange={(v) => setTweak('brandDisplay', v)}/>
      <TweakRadio label="Language"
        value={lang}
        options={[{value:'ru', label:'RU'}, {value:'en', label:'EN'}]}
        onChange={(v) => setLang(v)}/>

      <TweakSection label="Palette" />
      <TweakRadio label="Surface"
        value={tweaks.palette}
        options={[{value:'dark', label:'Dark'}, {value:'paper', label:'Paper'}]}
        onChange={(v) => setTweak('palette', v)}/>
      <TweakSelect label="Accent"
        value={tweaks.accentSwatch}
        options={[
          {value: 0, label: 'Indigo · Pink · Amber'},
          {value: 1, label: 'Electric Blue'},
          {value: 2, label: 'Acid Green'},
          {value: 3, label: 'Monochrome'},
        ]}
        onChange={(v) => setTweak('accentSwatch', Number(v))}/>

      <TweakSection label="Type" />
      <TweakSelect label="Heading"
        value={tweaks.headingFont}
        options={[
          {value: 'JetBrains Mono', label: 'JetBrains Mono (default)'},
          {value: 'Inter Tight', label: 'Inter Tight (sans)'},
          {value: 'Instrument Serif', label: 'Instrument Serif'},
        ]}
        onChange={(v) => setTweak('headingFont', v)}/>
      <TweakRadio label="Density"
        value={tweaks.density}
        options={[{value:'comfortable', label:'Comfy'}, {value:'tight', label:'Tight'}]}
        onChange={(v) => setTweak('density', v)}/>

      <TweakSection label="Hero animation" />
      <TweakSlider label="Intensity"
        min={0} max={200} step={10}
        value={tweaks.heroIntensity}
        onChange={(v) => setTweak('heroIntensity', v)}
        unit="%"/>

      <TweakSection label="Viewport" />
      <TweakRadio label="Mode"
        value={tweaks.viewportMode}
        options={[{value:'single', label:'Full'}, {value:'compare', label:'Compare'}]}
        onChange={(v) => setTweak('viewportMode', v)}/>
    </TweaksPanel>
  );
}

// ─────────────────────────────────────────────────────────────
// Bootstrap: check ?embed=1 mode for compare iframes
// ─────────────────────────────────────────────────────────────
function EmbedSite() {
  const params = new URLSearchParams(location.search);
  const lang = params.get('lang') || 'ru';
  const accentSwatch = Number(params.get('accent') || 0);
  const palette = params.get('palette') || 'dark';
  const density = params.get('density') || 'comfortable';
  const heroIntensity = Number(params.get('heroIntensity') || 100);
  const tweaks = { ...TWEAK_DEFAULTS, accentSwatch, palette, density, heroIntensity, brand: TWEAK_DEFAULTS.brand };
  const [langState, setLangState] = React.useState(lang);
  React.useEffect(() => { applyTweaksToDOM(tweaks); }, []);
  return <MainSite tweaks={tweaks} lang={langState} setLang={setLangState} />;
}

{
  const params = new URLSearchParams(location.search);
  const root = ReactDOM.createRoot(document.getElementById('root'));
  root.render(params.get('embed') === '1' ? <EmbedSite /> : <App />);
}
