/* global React, ReactDOM */
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

function shuffle(arr) {
  const a = arr.slice();
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

const SUPPORTED_LANGS = ['EN','TR','DE','FR','ES','PT','AR','JA','KO','ZH','RU','HI'];
const RTL_LANGS = new Set(['AR']);

function detectInitialLang() {
  try {
    const saved = localStorage.getItem('postai_lang');
    if (saved && SUPPORTED_LANGS.includes(saved)) return saved;
    const nav = (navigator.language || 'en').slice(0, 2).toUpperCase();
    if (SUPPORTED_LANGS.includes(nav)) return nav;
  } catch (e) {}
  return 'EN';
}

const LangContext = createContext({ lang: 'EN', setLang: () => {}, t: (k) => k });

function LangProvider({ children }) {
  const [lang, setLangState] = useState(detectInitialLang);
  useEffect(() => {
    document.documentElement.lang = lang.toLowerCase();
    document.documentElement.dir = RTL_LANGS.has(lang) ? 'rtl' : 'ltr';
  }, [lang]);
  const setLang = (l) => {
    setLangState(l);
    try { localStorage.setItem('postai_lang', l); } catch (e) {}
  };
  const t = (path) => {
    const dict = (window.PIXORIA_TRANSLATIONS && (window.PIXORIA_TRANSLATIONS[lang] || window.PIXORIA_TRANSLATIONS.EN)) || {};
    const fallback = (window.PIXORIA_TRANSLATIONS && window.PIXORIA_TRANSLATIONS.EN) || {};
    const parts = path.split('.');
    let cur = dict;
    for (const p of parts) { cur = cur && cur[p]; if (cur === undefined) break; }
    if (cur !== undefined) return cur;
    let fb = fallback;
    for (const p of parts) { fb = fb && fb[p]; if (fb === undefined) break; }
    return fb !== undefined ? fb : path;
  };
  return <LangContext.Provider value={{ lang, setLang, t }}>{children}</LangContext.Provider>;
}

function useT() { return useContext(LangContext); }

// ============== MOUSE GLOW ==============
function MouseGlow() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf = 0, tx = 0, ty = 0, x = 0, y = 0;
    const onMove = (e) => {
      tx = e.clientX;
      ty = e.clientY;
    };
    const tick = () => {
      x += (tx - x) * 0.10;
      y += (ty - y) * 0.10;
      el.style.transform = `translate(${x}px, ${y}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener('mousemove', onMove);
    tick();
    return () => { cancelAnimationFrame(raf); window.removeEventListener('mousemove', onMove); };
  }, []);
  return <div className="mouse-glow" ref={ref} />;
}

// ============== ANIMATED LOGO ==============
function PostaiLogo({ size = 32 }) {
  return (
    <div className="logo-sparkle" style={{ width: size, height: size }}>
      <img src="assets/logo-clear.png" alt="Postai" className="logo-img" />
      <div className="star" />
      <div className="star" />
      <div className="star" />
      <div className="star" />
    </div>
  );
}

// ============== DATA ==============
const EFFECT_CATEGORIES_FALLBACK = [
  { id: 'all', label: 'All' },
];
const EFFECTS_FALLBACK = [];

let _effectsCache = null;
let _effectsPromise = null;
function useEffectsData() {
  const [data, setData] = useState(_effectsCache ?? { categories: EFFECT_CATEGORIES_FALLBACK, effects: EFFECTS_FALLBACK });
  useEffect(() => {
    if (_effectsCache) return;
    if (!_effectsPromise) {
      _effectsPromise = fetch('effects.json').then(r => r.json()).then(d => { _effectsCache = d; return d; }).catch(() => null);
    }
    _effectsPromise.then(d => { if (d) setData(d); });
  }, []);
  return data;
}

function SmartImg({ src, alt, className = '', style }) {
  const [loaded, setLoaded] = useState(false);
  if (!src) return <div className={"smart-img-skeleton " + className} style={style} />;
  return (
    <img
      src={src}
      alt={alt}
      loading="lazy"
      decoding="async"
      onLoad={() => setLoaded(true)}
      className={className + ' smart-img' + (loaded ? ' loaded' : '')}
      style={style}
    />
  );
}

const FAQS = [
  { q: 'How does Postai work?', a: "Upload a photo, choose an effect or describe what you want, and our AI does the rest. You'll get a polished image or video back in seconds — ready to share." },
  { q: 'What kind of photos work best?', a: 'Clear, well-lit portraits where the face and body are visible give the best results. You can use selfies, full-body shots, or even old photos.' },
  { q: 'How are coins used?', a: 'Each generation (image or video) uses a small amount of coins depending on the effect type. New users start with free coins to explore. Top up anytime from the Profile tab.' },
  { q: 'Is my data private?', a: 'Yes. Your photos are processed securely and are not used to train any models. You can delete your account and all associated data from the app at any time.' },
  { q: 'Is Postai available on Android?', a: "Postai is iOS-only today. We're focused on making the iPhone experience as polished as possible before expanding to other platforms." },
  { q: 'Can I cancel my subscription?', a: 'Yes, anytime from your Apple ID subscription settings. Your access continues until the end of the current billing period.' },
];

const COIN_PACKS = [
  { coins: 100, price: '$1.99', meta: '~ 5 generations', icon: '◆' },
  { coins: 500, price: '$7.99', meta: '~ 25 generations · best value', icon: '◆◆', badge: 'Most popular', featured: true },
  { coins: 1500, price: '$19.99', meta: '~ 80 generations', icon: '◆◆◆' },
];

// ============== SHOWCASE ==============
const SHOWCASE_ACCENTS = ['#ff8a6b', '#d8a3ff', '#ffd166'];

function Showcase() {
  const { t } = useT();
  const { effects } = useEffectsData();
  const pool = useMemo(() => shuffle(effects.filter(e => e.image && e.outputType !== 'video')), [effects]);
  const picks = pool.slice(0, 3);
  const floats = pool.slice(3, 9).map((e, i) => ({
    label: e.name,
    color: ['#ffea00', '#ff5a8a', '#ffa000', '#b86bff', '#4ea6ff', '#7ad3ff'][i],
    cls: `sf-${i + 1}`,
  }));
  return (
    <section className="section showcase-section">
      <div className="container showcase-container">
        <div className="section-eyebrow-center">
          <span className="eyebrow">{t('showcase.eyebrow')}</span>
          <h2>{t('showcase.title1')}<br /><span className="accent">{t('showcase.title2')}</span></h2>
        </div>
        <div className="showcase-stage">
          {floats.map((f, i) => (
            <div key={i} className={`float-label showcase-float ${f.cls}`} style={{'--dot-color': f.color}}>
              {f.label}
            </div>
          ))}
          <div className="showcase-grid">
            {picks.map((s, i) => {
              const parts = s.name.split(' ');
              const light = parts.slice(0, -1).join(' ') || s.name;
              const bold = parts.length > 1 ? parts[parts.length - 1] : '';
              return (
                <div key={s.id} className="showcase-card" style={{'--accent': SHOWCASE_ACCENTS[i % SHOWCASE_ACCENTS.length]}}>
                  <div className="showcase-title">
                    <span className="showcase-title-light">{light}</span>
                    {bold && <span className="showcase-title-bold">{bold}</span>}
                  </div>
                  <SmartImg src={s.image} alt={s.name} className="showcase-img" />
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== BEFORE / AFTER ==============
function BeforeAfter() {
  const { t } = useT();
  const { effects } = useEffectsData();
  const options = useMemo(() => shuffle(effects.filter(e => e.image && e.before && e.outputType !== 'video')).slice(0, 7).map(e => ({
    id: e.id,
    label: e.name,
    before: e.before,
    after: e.image,
  })), [effects]);
  const fallback = { id: 'none', label: '—', before: null, after: null };
  const [activeId, setActiveId] = useState(null);
  const active = options.find(o => o.id === activeId) || options[0] || fallback;
  const [pos, setPos] = useState(50);
  const frameRef = useRef(null);
  const dragging = useRef(false);

  const update = (clientX) => {
    const rect = frameRef.current.getBoundingClientRect();
    const p = ((clientX - rect.left) / rect.width) * 100;
    setPos(Math.min(95, Math.max(5, p)));
  };
  const onDown = (e) => { dragging.current = true; update(e.clientX || e.touches[0].clientX); };
  const onMove = (e) => { if (dragging.current) update(e.clientX || e.touches[0].clientX); };
  const onUp = () => { dragging.current = false; };

  useEffect(() => {
    window.addEventListener('mousemove', onMove);
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchmove', onMove);
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('touchend', onUp);
    };
  }, []);

  return (
    <section className="section ba-section">
      <div className="container ba-grid">
        <div>
          <span className="eyebrow">{t('ba.eyebrow')}</span>
          <h2 className="h-section" style={{marginTop: 18, fontSize: 'clamp(36px, 5vw, 64px)'}}>
            {t('ba.title1')}<br />
            <span className="gold">{t('ba.title2')}</span>
          </h2>
          <p style={{color: 'var(--text-2)', fontSize: 17, marginTop: 24, lineHeight: 1.6, maxWidth: 460}}>
            {t('ba.desc')}
          </p>
          <div className="ba-pills">
            {options.map(o => (
              <button
                key={o.id}
                className={"ba-pill" + (active.id === o.id ? ' active' : '')}
                onClick={() => setActiveId(o.id)}
              >{o.label}</button>
            ))}
          </div>
        </div>

        <div className="ba-frame" ref={frameRef} onMouseDown={onDown} onTouchStart={onDown}>
          <div className="ba-img before" style={{backgroundImage: `url(${active.before})`}} />
          <div className="ba-img after" style={{
            backgroundImage: `url(${active.after})`,
            clipPath: `inset(0 0 0 ${pos}%)`,
          }} />
          <div className="ba-handle" style={{left: `${pos}%`}} />
          <div className="ba-tag before-tag">{t('ba.before')}</div>
          <div className="ba-tag after-tag">{t('ba.after')}{active.label}</div>
        </div>
      </div>
    </section>
  );
}

// ============== EFFECTS RAIL (infinite scroll) ==============
function EffectsRail() {
  const { effects } = useEffectsData();
  const withImg = useMemo(() => shuffle(effects.filter(e => e.image && e.outputType !== 'video')), [effects]);
  const row1 = withImg.slice(0, 8);
  const row2 = withImg.slice(8, 16);

  const renderRow = (items, reverse) => {
    if (items.length === 0) return <div className="effects-rail-mask" />;
    const doubled = [...items, ...items];
    return (
      <div className="effects-rail-mask">
        <div className={"effects-rail" + (reverse ? ' reverse' : '')}>
          {doubled.map((e, i) => (
            <div key={i} className="effects-rail-card" style={{backgroundImage: `url(${e.image})`}}>
              <div className="effects-rail-card-label">{e.name}</div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  return (
    <section className="effects-rail-section">
      {renderRow(row1, false)}
      {renderRow(row2, true)}
    </section>
  );
}

// ============== STEPS ==============
function Steps() {
  const { t } = useT();
  const data = useEffectsData();
  const { effects } = data;
  const selfies = data.selfies || [];
  const pool = useMemo(() => shuffle(effects.filter(e => e.image && e.outputType !== 'video')), [effects]);
  const tiles = pool.slice(0, 4);
  const portraitOne = pool[5];
  return (
    <section className="section" id="how">
      <div className="container">
        <div className="section-eyebrow-center">
          <span className="eyebrow">{t('steps.eyebrow')}</span>
          <h2>{t('steps.title1')} <span className="accent">{t('steps.title2')}</span></h2>
        </div>
        <div className="steps-grid">
          <div className="step-card step-art-1">
            <div className="step-art">
              <div className="step-art-icon">
                {tiles.map((e, i) => (
                  <div key={i} style={e.image ? { backgroundImage: `url(${e.image})`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined} />
                ))}
              </div>
            </div>
            <div className="step-num">01</div>
            <h3>{t('steps.s1Title')}</h3>
            <p>{t('steps.s1Desc')}</p>
          </div>
          <div className="step-card step-art-2">
            <div className="step-art">
              <div className="step-art-icon">
                <div style={selfies[0] ? { backgroundImage: `url(${selfies[0]})`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined} />
                <div style={selfies[1] ? { backgroundImage: `url(${selfies[1]})`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined} />
              </div>
            </div>
            <div className="step-num">02</div>
            <h3>{t('steps.s2Title')}</h3>
            <p>{t('steps.s2Desc')}</p>
          </div>
          <div className="step-card step-art-3">
            <div className="step-art">
              <div className="step-art-icon" style={portraitOne?.image ? { backgroundImage: `url(${portraitOne.image})`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined} />
            </div>
            <div className="step-num">03</div>
            <h3>{t('steps.s3Title')}</h3>
            <p>{t('steps.s3Desc')}</p>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== FEATURE BENTO ==============
function FeatureBento() {
  const { t } = useT();
  const { effects } = useEffectsData();
  const cards = useMemo(() => shuffle(effects.filter(e => e.image && e.outputType !== 'video')).slice(0, 4), [effects]);
  return (
    <section className="section" id="features">
      <div className="container">
        <div className="section-eyebrow-center">
          <span className="eyebrow">{t('bento.eyebrow')}</span>
          <h2>{t('bento.title1')} <span className="accent">{t('bento.title2')}</span></h2>
        </div>
        <div className="feature-bento">
          <div className="bento-card span-rows-2">
            <div className="bento-hero-art">
              {cards.map((e, i) => (
                <div key={i} className="card" style={e.image ? { backgroundImage: `url(${e.image})`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined} />
              ))}
              {Array.from({ length: Math.max(0, 4 - cards.length) }).map((_, i) => <div key={`fb${i}`} className="card" />)}
            </div>
            <div className="bento-big-num">120+</div>
            <h3>{t('bento.cinematic')}</h3>
            <p>{t('bento.cinematicDesc')}</p>
          </div>
          <div className="bento-card">
            <div className="bento-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
            </div>
            <h3>{t('bento.faceTitle')}</h3>
            <p>{t('bento.faceDesc')}</p>
          </div>
          <div className="bento-card">
            <div className="bento-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
            </div>
            <h3>{t('bento.langsTitle')}</h3>
            <p>{t('bento.langsDesc')}</p>
          </div>
          <div className="bento-card">
            <div className="bento-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z"/></svg>
            </div>
            <h3>{t('bento.cloudTitle')}</h3>
            <p>{t('bento.cloudDesc')}</p>
          </div>
          <div className="bento-card">
            <div className="bento-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>
            </div>
            <h3>{t('bento.widgetsTitle')}</h3>
            <p>{t('bento.widgetsDesc')}</p>
          </div>
          <div className="bento-card">
            <div className="bento-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
            </div>
            <h3>{t('bento.liveTitle')}</h3>
            <p>{t('bento.liveDesc')}</p>
          </div>
          <div className="bento-card">
            <div className="bento-icon">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
            </div>
            <h3>{t('bento.shareTitle')}</h3>
            <p>{t('bento.shareDesc')}</p>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== LANGUAGE PICKER ==============
const LANGUAGES = [
  { code: 'EN', label: 'English' },
  { code: 'TR', label: 'Türkçe' },
  { code: 'DE', label: 'Deutsch' },
  { code: 'FR', label: 'Français' },
  { code: 'ES', label: 'Español' },
  { code: 'PT', label: 'Português' },
  { code: 'AR', label: 'العربية' },
  { code: 'JA', label: '日本語' },
  { code: 'KO', label: '한국어' },
  { code: 'ZH', label: '简体中文' },
  { code: 'RU', label: 'Русский' },
  { code: 'HI', label: 'हिन्दी' },
];

function LanguagePicker() {
  const [open, setOpen] = useState(false);
  const { lang, setLang } = useT();
  const ref = useRef(null);
  const current = LANGUAGES.find(l => l.code === lang) || LANGUAGES[0];

  useEffect(() => {
    const onClick = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);

  return (
    <div className="lang-picker" ref={ref}>
      <button className="lang-btn" onClick={() => setOpen(o => !o)}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <circle cx="12" cy="12" r="10"/>
          <line x1="2" y1="12" x2="22" y2="12"/>
          <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
        </svg>
        <span className="lang-btn-code">{current.code}</span>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" className={"lang-chev" + (open ? ' open' : '')}>
          <polyline points="6 9 12 15 18 9"/>
        </svg>
      </button>
      <div className={"lang-menu" + (open ? ' open' : '')}>
        {LANGUAGES.map(l => (
          <button
            key={l.code}
            className={"lang-item" + (l.code === current.code ? ' active' : '')}
            onClick={() => { setLang(l.code); setOpen(false); }}
          >
            <span className="lang-name">{l.label}</span>
            <span className="lang-code">{l.code}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

// ============== UI BITS ==============
function NavBar({ page = 'home' }) {
  const { t } = useT();
  const isHome = page === 'home';
  const link = (anchor) => isHome ? `#${anchor}` : `index.html#${anchor}`;
  return (
    <nav className="nav">
      <a href={isHome ? '#' : 'index.html'} className="nav-brand">
        <PostaiLogo size={28} />
        <span>Postai</span>
      </a>
      <div className="nav-links">
        <a href={link('effects')} className={"nav-link" + (isHome ? ' active' : '')}>{t('nav.effects')}</a>
        <a href={link('how')} className="nav-link">{t('steps.eyebrow')}</a>
        <a href={link('features')} className="nav-link">{t('nav.features')}</a>
        <a href={link('faq')} className="nav-link">{t('nav.faq')}</a>
      </div>
      <div className="nav-actions">
        <a href="#download" className="nav-cta">{t('nav.download')}</a>
        <LanguagePicker />
      </div>
    </nav>
  );
}

function StoreButton() {
  return (
    <a href="#download" className="btn-store" title="Download on the App Store">
      <svg width="22" height="26" viewBox="0 0 22 26" fill="white" xmlns="http://www.w3.org/2000/svg">
        <path d="M18.6 13.86c-.03-3.13 2.55-4.62 2.66-4.7-1.45-2.12-3.71-2.41-4.51-2.45-1.92-.19-3.74 1.13-4.71 1.13-.97 0-2.47-1.1-4.06-1.07-2.09.03-4 1.21-5.07 3.07-2.16 3.74-.55 9.27 1.55 12.31 1.03 1.49 2.26 3.16 3.86 3.1 1.55-.06 2.13-1 4.01-1 1.87 0 2.4 1 4.04.97 1.66-.03 2.72-1.51 3.74-3 1.18-1.72 1.66-3.39 1.69-3.48-.04-.01-3.23-1.24-3.26-4.92zm-3.1-9.04C16.36 3.74 16.95 2.27 16.78.81c-1.27.05-2.81.84-3.7 1.91-.79.94-1.5 2.46-1.31 3.89 1.42.11 2.87-.72 3.74-1.78z"/>
      </svg>
      <div>
        <span className="label-sm">Download on the</span>
        <span className="label-lg">App Store</span>
      </div>
    </a>
  );
}

// ============== HERO V2 (Expecto-style) ==============
const HERO_SHOTS = [
  { src: 'assets/SS01.png', label: 'Sun Kissed', accent: '#ffa000' },
  { src: 'assets/marketing-cozy-rose.png', label: 'Cozy Rose Grace', accent: '#ff8a6b' },
  { src: 'assets/SS02.png', label: 'Pastel Bloom', accent: '#ff5a8a' },
  { src: 'assets/marketing-pastel-bloom.png', label: 'Pastel Bloom Grace', accent: '#d8a3ff' },
  { src: 'assets/SS03.png', label: 'Cozy Rose Grace', accent: '#b86bff' },
  { src: 'assets/marketing-sun-kissed.png', label: 'Sun Kissed', accent: '#ffd166' },
  { src: 'assets/SS04.png', label: 'Magazine Cover', accent: '#4ea6ff' },
  { src: 'assets/SS05.png', label: 'Night Drive', accent: '#ffea00' },
];

function Hero() {
  const { t } = useT();
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    const id = setInterval(() => setIdx(i => (i + 1) % HERO_SHOTS.length), 3500);
    return () => clearInterval(id);
  }, []);
  const current = HERO_SHOTS[idx];
  const next = HERO_SHOTS[(idx + 1) % HERO_SHOTS.length];
  const peek = HERO_SHOTS[(idx + 2) % HERO_SHOTS.length];
  return (
    <section className="hero-v2">
      <div className="hero-v2-bg" />
      <div className="container hero-v2-grid">
        <div>
          <div className="hero-v2-pill">{t('hero.pill')}</div>
          <h1>
            {t('hero.title1')}<br />
            {t('hero.title2')}<br />
            <span className="accent">{t('hero.title3')}</span>
          </h1>
          <p className="hero-v2-sub">{t('hero.sub')}</p>
          <div className="hero-cta">
            <StoreButton />
            <a href="#effects" className="btn btn-ghost">{t('hero.explore')}</a>
          </div>
        </div>

        <div className="hero-phone-stage">
          <div className="phone-shell">
            <div className="phone-notch" />
            <div className="phone-screen">
              {HERO_SHOTS.map((s, i) => (
                <img
                  key={i}
                  src={s.src}
                  alt={s.label}
                  className={"phone-screen-img" + (i === idx ? ' active' : '')}
                />
              ))}
            </div>
          </div>
          <div className="float-label fl-1" key={'fl1-' + idx} style={{'--dot-color': current.accent}}>
            {current.label}
          </div>
          <div className="float-label fl-2" key={'fl2-' + idx} style={{'--dot-color': next.accent}}>
            {next.label}
          </div>
          <div className="float-label fl-3" key={'fl3-' + idx} style={{'--dot-color': peek.accent}}>
            {peek.label}
          </div>
          <div className="float-label fl-4" key={'fl4-' + idx} style={{'--dot-color': HERO_SHOTS[(idx + 3) % HERO_SHOTS.length].accent}}>
            {HERO_SHOTS[(idx + 3) % HERO_SHOTS.length].label}
          </div>
        </div>
      </div>

      <div className="container">
        <div className="stats-v2">
          <div>
            <div className="stat-num-v2">120<span className="suffix">+</span></div>
            <div className="stat-label-v2">{t('stats.effects')}</div>
          </div>
          <div>
            <div className="stat-num-v2">2<span className="suffix">M</span></div>
            <div className="stat-label-v2">{t('stats.creations')}</div>
          </div>
          <div>
            <div className="stat-num-v2">12</div>
            <div className="stat-label-v2">{t('stats.languages')}</div>
          </div>
          <div>
            <div className="stat-num-v2">4.9</div>
            <div className="stat-label-v2">{t('stats.rating')}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ============== MARQUEE ==============
function Marquee() {
  const items = ['Floral Grace', 'Beach & Summer', 'Winter', 'Valentine\'s', 'Instastory', 'AI Editor', 'Pop Out', 'Sun Kissed', 'Vacay', 'Western Cowboy'];
  const row = (
    <>
      {items.map((it, i) => (
        <span key={i} className="marquee-item">{it}<span className="dot" /></span>
      ))}
    </>
  );
  return (
    <div className="marquee">
      <div className="marquee-track">
        {row}{row}
      </div>
    </div>
  );
}

// ============== EFFECTS GRID ==============
function Effects() {
  const { t } = useT();
  const [active, setActive] = useState('all');
  const { categories, effects } = useEffectsData();
  const filtered = active === 'all'
    ? effects.filter(e => e.outputType !== 'video').slice(0, 12)
    : effects.filter(e => e.cat === active);
  return (
    <section className="section" id="effects">
      <div className="container">
        <div className="effects-head">
          <div>
            <span className="eyebrow">{t('effects.eyebrow')}</span>
            <h2 className="h-section" style={{marginTop: 18}}>
              {t('effects.title1')}<br /><span className="gold">{t('effects.title2')}</span>
            </h2>
          </div>
          <div className="effects-tabs">
            {categories.map(c => (
              <button
                key={c.id}
                className={"effects-tab" + (active === c.id ? ' active' : '')}
                onClick={() => setActive(c.id)}
              >{c.id === 'all' ? t('effects.all') : c.label}</button>
            ))}
          </div>
        </div>
        <div className="effects-grid">
          {filtered.map((e) => (
            <div key={e.id} className="effect-card">
              <div className="effect-card-art">
                <SmartImg src={e.image} alt={e.name} className="effect-card-img" />
              </div>
              {e.tag && <div className={"effect-card-tag" + (e.tag === 'New' ? ' new' : e.tag === 'Video' ? ' video' : '')}>{e.tag}</div>}
              <div className="effect-card-overlay">
                <div className="effect-card-meta">
                  <div className="effect-card-name">{e.name}</div>
                  <div className="effect-card-stats">
                    <span>♡ {e.likes}</span>
                    <span>▷ {e.plays}</span>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============== FEATURE BLOCKS ==============
function FeatureBlock({ num, eyebrow, title, titleAccent, desc, points, img, reverse }) {
  return (
    <div className={"feature-block" + (reverse ? ' reverse' : '')}>
      <div>
        <div className="feature-num">{num}</div>
        <span className="eyebrow">{eyebrow}</span>
        <h2 className="h-section feature-title" style={{marginTop: 18}}>
          {title}{titleAccent && <><br /><span className="gold">{titleAccent}</span></>}
        </h2>
        <p className="feature-desc">{desc}</p>
        <ul className="feature-points">
          {points.map((p, i) => <li key={i}>{p}</li>)}
        </ul>
      </div>
      <div className="feature-art">
        <img src={img} alt="" />
      </div>
    </div>
  );
}

function Features() {
  return (
    <section className="section" id="features">
      <div className="container">
        <FeatureBlock
          num="01 — Trends"
          eyebrow="Viral effects"
          title="Tap into trends"
          titleAccent="before they peak."
          desc="Postai's editorial team curates the effects exploding on TikTok, Reels, and Stories — so you ride the wave instead of chasing it."
          points={[
            'New effect packs every week',
            'Curated categories: Floral, Winter, Beach, Y2K and more',
            'Save your favorites for one-tap reuse',
          ]}
          img="assets/SS02.png"
        />
        <FeatureBlock
          reverse
          num="02 — Sets"
          eyebrow="Multi-shot stories"
          title="One photo."
          titleAccent="A whole set."
          desc="Single-pose effects are old news. Postai generates entire photo sets — 20+ images in one consistent character — so your feed always looks like a real shoot."
          points={[
            'Up to 47 images per generation',
            'Consistent identity across every shot',
            'Mix portrait, action, and scene shots automatically',
          ]}
          img="assets/SS03.png"
        />
        <FeatureBlock
          num="03 — Stories"
          eyebrow="Instastory generator"
          title="Stop the scroll"
          titleAccent="every single time."
          desc="Build full Instagram Story carousels in one go. Postai drafts the moodboard, the captions, and the visuals — you just hit post."
          points={[
            'Caption suggestions in 12 languages',
            'Auto-cropped for Stories, Reels, and TikTok',
            'Export to camera roll or share directly',
          ]}
          img="assets/SS04.png"
        />
        <FeatureBlock
          reverse
          num="04 — AI Editor"
          eyebrow="Just describe it"
          title="Talk to your photo."
          titleAccent="It listens."
          desc="Want longer hair? Different outfit? A new background? Type what you want. Postai's AI editor handles the rest — no sliders, no masks, no learning curve."
          points={[
            'Natural-language prompts',
            'Iterative editing — refine in chat',
            'Preserves likeness on every pass',
          ]}
          img="assets/SS05.png"
        />
      </div>
    </section>
  );
}

// ============== STATS ==============
function Stats() {
  return (
    <section className="stats">
      <div className="container stats-grid">
        <div><div className="stat-num">2M+</div><div className="stat-label">Creations made</div></div>
        <div><div className="stat-num">120+</div><div className="stat-label">Effects in library</div></div>
        <div><div className="stat-num">4.9★</div><div className="stat-label">App Store rating</div></div>
        <div><div className="stat-num">62</div><div className="stat-label">Countries served</div></div>
      </div>
    </section>
  );
}

// ============== PRICING ==============
function Pricing() {
  return (
    <section className="section" id="pricing">
      <div className="container">
        <div style={{textAlign: 'center', maxWidth: 720, margin: '0 auto 16px'}}>
          <span className="eyebrow">Coins</span>
          <h2 className="h-section" style={{marginTop: 18}}>
            Pay only for what<br /><span className="gold">you actually create.</span>
          </h2>
          <p style={{color: 'var(--text-2)', fontSize: 17, marginTop: 18, lineHeight: 1.6}}>
            Coins power every generation. Top up once, use them whenever you want — they don't expire.
          </p>
        </div>
        <div className="pricing-grid">
          {COIN_PACKS.map(p => (
            <div key={p.coins} className={"coin-card" + (p.featured ? ' featured' : '')}>
              {p.badge && <div className="coin-badge">{p.badge}</div>}
              <div className="coin-icon" style={{color: 'var(--gold-text)'}}>{p.icon}</div>
              <div>
                <span className="coin-amount">{p.coins.toLocaleString()}</span>
                <span className="coin-amount-suffix">coins</span>
              </div>
              <div className="coin-price">{p.price}</div>
              <div className="coin-meta">{p.meta}</div>
            </div>
          ))}
        </div>
        <p style={{textAlign: 'center', color: 'var(--text-3)', fontSize: 13, marginTop: 32}}>
          One-time purchase. No subscription required. Refunds via Apple within 14 days.
        </p>
      </div>
    </section>
  );
}

// ============== FAQ ==============
function FAQ() {
  const { t } = useT();
  const [open, setOpen] = useState(0);
  return (
    <section className="section" id="faq">
      <div className="container">
        <div style={{textAlign: 'center', marginBottom: 56}}>
          <span className="eyebrow">{t('faq.eyebrow')}</span>
          <h2 className="h-section" style={{marginTop: 18}}>
            {t('faq.title')}
          </h2>
        </div>
        <div className="faq-list">
          {FAQS.map((f, i) => (
            <div key={i} className={"faq-item" + (open === i ? ' open' : '')}>
              <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)}>
                <span>{f.q}</span>
                <span className="faq-q-icon">+</span>
              </button>
              <div className="faq-a"><div className="faq-a-inner">{f.a}</div></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ============== FINAL CTA ==============
function FinalCTA() {
  const { t } = useT();
  return (
    <section className="container" id="download">
      <div className="cta-card">
        <div className="cta-pill">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M18.6 13.86c-.03-3.13 2.55-4.62 2.66-4.7-1.45-2.12-3.71-2.41-4.51-2.45-1.92-.19-3.74 1.13-4.71 1.13-.97 0-2.47-1.1-4.06-1.07-2.09.03-4 1.21-5.07 3.07-2.16 3.74-.55 9.27 1.55 12.31 1.03 1.49 2.26 3.16 3.86 3.1 1.55-.06 2.13-1 4.01-1 1.87 0 2.4 1 4.04.97 1.66-.03 2.72-1.51 3.74-3 1.18-1.72 1.66-3.39 1.69-3.48-.04-.01-3.23-1.24-3.26-4.92zm-3.1-9.04C16.36 3.74 16.95 2.27 16.78.81c-1.27.05-2.81.84-3.7 1.91-.79.94-1.5 2.46-1.31 3.89 1.42.11 2.87-.72 3.74-1.78z"/></svg>
          <span>{t('cta.pill')}</span>
        </div>
        <h2 className="cta-title">
          {t('cta.titlePre')}<br />
          {t('cta.titleIn')} <span className="cta-highlight">{t('cta.highlight')}</span>
        </h2>
        <p className="cta-sub">{t('cta.sub')}</p>
        <a href="#" className="cta-store-btn">
          <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M18.6 13.86c-.03-3.13 2.55-4.62 2.66-4.7-1.45-2.12-3.71-2.41-4.51-2.45-1.92-.19-3.74 1.13-4.71 1.13-.97 0-2.47-1.1-4.06-1.07-2.09.03-4 1.21-5.07 3.07-2.16 3.74-.55 9.27 1.55 12.31 1.03 1.49 2.26 3.16 3.86 3.1 1.55-.06 2.13-1 4.01-1 1.87 0 2.4 1 4.04.97 1.66-.03 2.72-1.51 3.74-3 1.18-1.72 1.66-3.39 1.69-3.48-.04-.01-3.23-1.24-3.26-4.92zm-3.1-9.04C16.36 3.74 16.95 2.27 16.78.81c-1.27.05-2.81.84-3.7 1.91-.79.94-1.5 2.46-1.31 3.89 1.42.11 2.87-.72 3.74-1.78z"/></svg>
          <div className="cta-store-text">
            <span className="cta-store-label">{t('cta.buttonLabel')}</span>
            <span className="cta-store-name">{t('cta.buttonStore')}</span>
          </div>
        </a>
      </div>
    </section>
  );
}

// ============== FOOTER ==============
function Footer() {
  const { t } = useT();
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="footer-brand">
              <div className="nav-brand-icon" style={{width: 36, height: 36}} />
              <span>Postai</span>
            </div>
            <p className="footer-tagline">{t('footer.tagline')}</p>
          </div>
          <div className="footer-col">
            <div className="footer-col-title">{t('footer.product')}</div>
            <ul>
              <li><a href="#effects">{t('nav.effects')}</a></li>
              <li><a href="#features">{t('nav.features')}</a></li>
              <li><a href="#pricing">{t('nav.pricing')}</a></li>
              <li><a href="#download">{t('nav.download')}</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <div className="footer-col-title">{t('footer.support')}</div>
            <ul>
              <li><a href="help.html">{t('nav.help')}</a></li>
              <li><a href="mailto:kadiraktastr@gmail.com">Contact</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <div className="footer-col-title">{t('footer.legal')}</div>
            <ul>
              <li><a href="terms.html">{t('footer.terms')}</a></li>
              <li><a href="privacy.html">{t('footer.privacy')}</a></li>
              <li><a href="subscription-policy.html">{t('footer.subs')}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} Postai · Crafted by Kadir Aktaş</span>
          <span>Made for iOS · Available on the App Store</span>
        </div>
      </div>
    </footer>
  );
}

// ============== TWEAKS ==============
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentHue": 38,
  "darkMode": true,
  "headlineStyle": "Turn Any Photo Into Pure Content",
  "showLaurel": true
}/*EDITMODE-END*/;

function PostaiTweaks() {
  const { TweaksPanel, TweakSection, TweakSlider, TweakToggle, TweakText } = window.Tweaks || {};
  const { useTweaks } = window.Tweaks || {};
  if (!TweaksPanel) return null;
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    document.documentElement.style.setProperty('--gold-text', `oklch(0.78 0.18 ${tweaks.accentHue})`);
    document.documentElement.style.setProperty('--gold-1', `oklch(0.72 0.20 ${tweaks.accentHue})`);
    document.documentElement.style.setProperty('--gold-2', `oklch(0.86 0.18 ${tweaks.accentHue + 22})`);
    document.documentElement.style.setProperty('--gold-glow', `oklch(0.72 0.20 ${tweaks.accentHue} / 0.35)`);
    document.documentElement.dataset.theme = tweaks.darkMode ? 'dark' : 'light';
  }, [tweaks]);

  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Brand">
        <TweakSlider label="Accent hue" value={tweaks.accentHue} min={0} max={360} step={1}
          onChange={(v) => setTweak('accentHue', v)} />
        <TweakToggle label="Dark mode" value={tweaks.darkMode}
          onChange={(v) => setTweak('darkMode', v)} />
      </TweakSection>
      <TweakSection title="Hero">
        <TweakToggle label="Show #1 laurel" value={tweaks.showLaurel}
          onChange={(v) => setTweak('showLaurel', v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

// ============== APP ==============
function App() {
  return (
    <>
      <MouseGlow />
      <NavBar page="home" />
      <Hero />
      <Marquee />
      <BeforeAfter />
      <EffectsRail />
      <Steps />
      <Effects />
      <FeatureBento />
      <Features />
      <Pricing />
      <FAQ />
      <FinalCTA />
      <Footer />
      <PostaiTweaks />
    </>
  );
}

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