// Main app — home + router

// Mağazadaki eski uygulama sürümlerinin Hakkında ekranından açtığı gizlilik yolları.
// Uygulamalar artık /gizlilik'e gidiyor; bu takma adlar güncellemeyen kullanıcılar için durur.
const LEGACY_PRIVACY_PATHS = new Map([
  ['/zikirmatik/privacy', 'zikirmatik'],
  ['/kelime-bul/privacy', 'kelimebul'],
  ['/ramazan-imsakiyesi/privacy', 'ramazan'],
]);

// Ana sayfa arka planı. Video yüklenene kadar .hh-sky gradyanı görünür.
const HOME_BG = { image: null, mp4: 'assets/aster.webm' };

// TR kanonik yol → uygulama anahtarı
const APP_ROUTES = { '/ramazan-imsakiyesi': 'ramazan' };
APPS.forEach(a => { APP_ROUTES[a.route] = a.key; });
// Noctavia'nın eski alt sayfaları artık aynı sayfanın bölümleri.
const NOCTAVIA_SECTIONS = ['sesli-yorum', 'ruya-sozlugu', 'tema-analizi', 'ruya-gunlugu', 'premium'];

function DiceWord({ text, accentLast = true }) {
  const t = useT();
  const [run, setRun] = useState(0);
  const chars = [...text];
  return (
    <span className="dice-word" key={run} onClick={() => setRun(r => r + 1)} title={t.ui.replay}>
      {chars.map((ch, i) => {
        const acc = accentLast && i === chars.length - 1;
        return (
          <span key={i} className={'dice ' + (acc ? 'dice-acc' : '')} style={{ '--d': 150 + i * 110 + 'ms' }}>
            <span className="dice-ghost">{ch}</span>
            <span className="dice-cube">
              <span className="df df0">{ch}</span><span className="df df1">{ch}</span><span className="df df2">{ch}</span><span className="df df3">{ch}</span>
            </span>
          </span>
        );
      })}
    </span>
  );
}

function HeroBackdrop() {
  return (
    <div className="hh-bg">
      <div className="hh-sky"><i className="hh-stars"></i><i className="hh-neb n1"></i><i className="hh-neb n2"></i><i className="hh-neb n3"></i><i className="hh-horizon"></i></div>
      {HOME_BG.image && <div className="hh-img" style={{ backgroundImage: `url(${HOME_BG.image})` }}></div>}
      {HOME_BG.mp4 && <video className="hh-video" src={HOME_BG.mp4} autoPlay muted loop playsInline></video>}
      <div className="hh-shade"></div>
    </div>
  );
}

function HomeHero() {
  const t = useT();
  const ref = useRef(null);
  const p = useScrollProgress(ref);
  const total = APPS.length;
  const pad2 = (n) => String(n).padStart(2, '0');
  const rise = easeOut(clamp01((p - 0.04) / 0.3));
  const cyc = clamp01((p - 0.36) / 0.6);
  const idx = Math.min(total - 1, Math.floor(cyc * total)) || 0;
  const app = APPS[idx] || APPS[0];
  const x = appText(t, app.key);
  const infoOn = rise > 0.92;
  const logoT = `translate(-50%, calc(-50% + ${(1 - rise) * 80}vh)) rotate(${(1 - rise) * -10}deg) scale(${0.82 + rise * 0.18})`;
  return (
    <section ref={ref} className="hh" data-screen-label="Home hero">
      <div className={'hh-sticky ' + (HOME_BG.image || HOME_BG.mp4 ? 'hh-dark' : '')} style={{ '--c': app.color, '--g': app.glow || app.color }}>
        <HeroBackdrop />
        <div className="hh-glow" style={{ opacity: rise }}></div>
        <div className="hh-meta"><span>{t.ui.studio}</span><span>{t.home.heroEyebrow}</span><span>{pad2(total)} {t.ui.appsCount}</span></div>
        <h1 className="hh-word" aria-label="kolabs." style={{ transform: `translate(-50%,-50%) scale(${1 - rise * 0.08})`, opacity: 1 - rise * 0.85, filter: `blur(${rise * 6}px)` }}>
          <DiceWord text="kolabs." />
        </h1>
        <Link to={app.route} className="hh-logo" aria-label={t.ui.goTo(x.name)} style={{ transform: logoT }}>{APPS.map((ap, i) => <img key={ap.key} className={'hl ' + (i === idx ? 'on' : i < idx ? 'past' : '')} src={ap.logo} alt={t.appsMeta[ap.key].name} />)}</Link>
        <div className={'hh-info hh-info-l ' + (infoOn ? 'on' : '')}>
          <div className="hh-count">{pad2(idx + 1)}<span>/{pad2(total)}</span></div>
          <div className="hh-name" key={app.key}>{x.card.name}</div>
          <div className="hh-cat">{x.card.category}</div>
          <p className="hh-tag hh-tag-m" key={'m' + app.key}>{x.card.tagline}</p>
        </div>
        <div className={'hh-info hh-info-r ' + (infoOn ? 'on' : '')}>
          <p className="hh-tag" key={app.key}>{x.card.tagline}</p>
          <StoreButtons app={app} variant="glass" small pending={app.soon ? t.home.statusSoon : null} />
          <Link to={app.route} className="hh-more">{t.ui.explore}</Link>
          <div className="hh-dots">{APPS.map((a, i) => <i key={i} className={i === idx ? 'on' : ''}></i>)}</div>
        </div>
        <div className="hh-bottom" style={{ opacity: 1 - rise * 2.2 }}>
          <div className="glass-pill"><span>{t.home.heroTagline}</span><b>{t.ui.scroll}</b></div>
        </div>
      </div>
    </section>
  );
}

function Manifesto() {
  const t = useT();
  const ref = useRef(null);
  const p = useScrollProgress(ref);
  const words = t.ui.manifestoText.split(' ');
  const lit = Math.floor(clamp01((p - 0.1) / 0.7) * words.length);
  return (
    <section ref={ref} className="mf" id="manifesto" data-screen-label="Manifesto">
      <div className="mf-sticky wrap">
        <SectionLabel num="01">{t.nav.manifesto}</SectionLabel>
        <p className="mf-text">{words.map((w, i) => <span key={i} className={i < lit ? 'lit' : ''}>{w} </span>)}</p>
      </div>
    </section>
  );
}

function Principles() {
  const t = useT();
  return (
    <section className="wrap pr">
      {t.home.principles.map((it, i) => (
        <Reveal key={i} className="pr-row" delay={i * 80}>
          <span className="pr-n">{String(i + 1).padStart(2, '0')}</span><h3 className="pr-t">{it.title}</h3><p className="pr-d">{it.desc}</p>
        </Reveal>
      ))}
    </section>
  );
}

function HomeCta() {
  const t = useT();
  return (
    <section className="hcta wrap">
      <SectionLabel num="02">{t.ui.storesLabel}</SectionLabel>
      <Reveal as="h2" className="h-xxl">{t.ui.storesTitle}</Reveal>
      <div className="hcta-row">
        <p>{t.ui.storesText}</p>
        <div className="btn-row">
          <a className="btn btn-solid" href={PLAY_DEV} target="_blank" rel="noopener"><span>{t.ui.devPlay}</span><span className="btn-ar">↗</span></a>
          <a className="btn btn-line" href={APPLE_DEV} target="_blank" rel="noopener"><span>{t.ui.devApple}</span><span className="btn-ar">↗</span></a>
        </div>
      </div>
    </section>
  );
}

function Home() {
  return (
    <main className="home">
      <HomeHero />
      <Manifesto />
      <Principles />
      <HomeCta />
    </main>
  );
}

function NotFound() {
  const t = useT();
  return <main className="wrap nf"><h1 className="h-xxl">404.</h1><p>{t.notFound.h2}</p><Link to="/" className="btn btn-solid">{t.notFound.cta}</Link></main>;
}

// Tema tercihi tarayıcıda kalsın; okunamazsa koyu tema.
function readTheme() {
  try { const v = localStorage.getItem('kolabs-theme'); if (v === 'light' || v === 'dark') return v; } catch (e) {}
  return 'dark';
}

function App() {
  const fullPath = usePathRoute();
  // Canonicalize to TR form for route matching (handles both /foo and /en/foo).
  const path = toTrCanonical(fullPath).replace(/(.)\/+$/, '$1');
  const [theme, setThemeState] = useState(readTheme);
  const setTheme = (v) => { setThemeState(v); try { localStorage.setItem('kolabs-theme', v); } catch (e) {} };
  useEffect(() => { document.documentElement.setAttribute('data-theme', theme); }, [theme]);

  // If the URL isn't canonical for its language (e.g. legacy `/en/sesli-yorum`
  // or `/en/kelime-bul`), silently rewrite to canonical without adding a
  // history entry. Old URLs keep working but search engines see the new ones.
  useEffect(() => {
    const lang = langFromPath(fullPath);
    const canonical = pathForLang(fullPath, lang);
    if (canonical !== fullPath) window.history.replaceState({}, '', canonical);
  }, [fullPath]);

  const parts = path.split('/').filter(Boolean);
  const base = '/' + (parts[0] || '');
  const appKey = APP_ROUTES[base];
  // Eski URL'lerde Türkçe karakterli varyantlar da var (/noctavia/rüya-sözlüğü).
  const sub = parts[1] ? parts[1].normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/ı/g, 'i') : null;

  let page;
  if (path === '/' || path === '') page = <Home />;
  else if (path === '/gizlilik' || path === '/privacy' || LEGACY_PRIVACY_PATHS.has(path)) page = <PrivacyPolicy key={path} initialApp={LEGACY_PRIVACY_PATHS.get(path)} />;
  else if (path === '/kullanim-sartlari' || path === '/terms') page = <TermsOfService />;
  else if (deletionRoute(path)) {
    // Mağaza formlarına giren adresler: /veri-silme/<uygulama>. Eşleşmeyi
    // deletion-pages.jsx yapıyor, iki dilin slug'ını da o biliyor.
    const r = deletionRoute(path);
    page = r.kind === 'hub' ? <DataDeletionHub /> : <DataDeletionApp app={r.app} />;
  }
  else if (path.startsWith('/z/')) page = <ChainInviteLanding kind="chain" />;
  else if (path.startsWith('/u/')) page = <ChainInviteLanding kind="friend" />;
  else if (appKey && parts.length === 1) page = <AppPage key={appKey} appKey={appKey} />;
  else if (appKey === 'noctavia' && parts.length === 2 && NOCTAVIA_SECTIONS.includes(sub)) page = <AppPage key={appKey} appKey={appKey} sub={sub} />;
  else page = <NotFound />;

  // Update title + per-page hreflang + og:url canonical
  const tApp = useT();
  useEffect(() => {
    const name = appKey && parts.length <= 2 ? tApp.home.apps[appKey].name : null;
    document.title = name ? `${name} — kolabs.` : `kolabs. — ${path === '/' ? tApp.home.title : path}`;
    const origin = window.location.origin && window.location.origin.startsWith('http')
      ? window.location.origin : 'https://kolabs.tr';
    const trUrl = origin + window.pathForLang(fullPath, 'tr');
    const enUrl = origin + window.pathForLang(fullPath, 'en');
    const setAlt = (lang, url) => {
      let el = document.querySelector(`link[rel="alternate"][hreflang="${lang}"]`);
      if (!el) {
        el = document.createElement('link');
        el.setAttribute('rel', 'alternate');
        el.setAttribute('hreflang', lang);
        document.head.appendChild(el);
      }
      el.setAttribute('href', url);
    };
    setAlt('tr', trUrl);
    setAlt('en', enUrl);
    setAlt('x-default', trUrl);
    const ogUrl = document.querySelector('meta[property="og:url"]');
    if (ogUrl) ogUrl.setAttribute('content', origin + fullPath);
  }, [fullPath, path, tApp]);

  return (
    <>
      <Nav current={path} theme={theme} setTheme={setTheme} />
      {page}
      <Footer />
      <TweaksPanel title="Tweaks">
        <TweakSection label="Görünüm">
          <TweakRadio label="Tema" value={theme} options={[{ value: 'dark', label: 'Koyu' }, { value: 'light', label: 'Açık' }]} onChange={setTheme} />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <LangProvider><App /></LangProvider>
);
setTimeout(() => {
  const s = document.getElementById('splash');
  if (s) { s.classList.add('hide'); setTimeout(() => s.remove(), 700); }
}, 900);
