
/* global React */
const { useState, useEffect, useRef, useLayoutEffect } = React;

function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { rootMargin: "-10% 0px -10% 0px", threshold: 0.1 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

function Nav({ lang, setLang, t, appearance }) {
  const [stuck, setStuck] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false); // MOBİL MENÜ KONTROLÜ

  useEffect(() => {
    const onScroll = () => setStuck(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const langs = [
  { code: "tr", label: "TR" },
  { code: "en", label: "EN" },
  { code: "de", label: "DE" }];

  return (
    <nav className="nav" data-stuck={stuck}>
      <a href="#top" className="nav__logo" aria-label="Sözeri Law">
        <img 
          src={appearance?.logoUrl || "assets/logo.png"} 
          alt="Sözeri Law" 
          style={{ height: appearance?.desktopLogoSize ? `${appearance.desktopLogoSize}px` : "70px" }} 
        />
      </a>

      {/* AÇILIR MENÜ LİNKLERİ */}
      <div className={`nav__links ${menuOpen ? 'nav__links--open' : ''}`}>
        <a href="#about" onClick={() => setMenuOpen(false)}>{t.nav.about}</a>
        <a href="#practice" onClick={() => setMenuOpen(false)}>{t.nav.practice}</a>
        <a href="#approach" onClick={() => setMenuOpen(false)}>{t.nav.approach}</a>
        <a href="blog.html" onClick={() => setMenuOpen(false)}>Blog</a>
        <a href="#contact" onClick={() => setMenuOpen(false)}>{t.nav.contact}</a>
      </div>

      {/* SAĞ TARAF (Dil, Randevu ve Hamburger Menü) */}
      <div className="nav__right" style={{ display: "flex", alignItems: "center" }}>
        <div className="lang">
          {langs.map((l, i) => <React.Fragment key={l.code}>
              <button
              data-active={lang === l.code}
              onClick={() => setLang(l.code)}>
                {l.label}
              </button>
              {i < langs.length - 1 && <span>/</span>}
            </React.Fragment>
          )}
        </div>
        
        {/* RANDEVU BUTONU (Mobilde adminden kapatıldıysa hide-on-mobile class'ı alır) */}
        {appearance?.showAppointment !== false && (
          <a href="#cta" className={`btn-cta ${appearance?.showMobileAppointment === false ? 'hide-on-mobile' : ''}`}>
            <span className="btn-cta__dot" />
            {t.nav.appointment}
          </a>
        )}

        {/* MOBİL MENÜ BUTONU (EN SAĞA EKLENDİ) */}
        {appearance?.showMobileMenu && (
          <button className="hamburger" onClick={() => setMenuOpen(!menuOpen)}>
            {menuOpen ? "✕" : "☰"}
          </button>
        )}
      </div>
    </nav>);
}

function Hero({ t, siteData }) {
  const videoRef = useRef(null);
  const heroRef = useRef(null);

  useEffect(() => {
    let raf;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        if (!videoRef.current || !heroRef.current) return;
        const rect = heroRef.current.getBoundingClientRect();
        const h = window.innerHeight;
        const progress = Math.max(0, Math.min(1, -rect.top / h));
        const scale = 1 + progress * 0.12;
        const y = progress * 60;
        videoRef.current.style.transform = `scale(${scale}) translateY(${y}px)`;
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <section className="hero" ref={heroRef} id="top">
      <video ref={videoRef} className="hero__video" src="assets/bg.mp4" autoPlay muted loop playsInline />
      <div className="hero__overlay" /><div className="hero__grain" />
      <div className="hero__content">
        <div>
          <div className="hero__eyebrow">{siteData?.heroEyebrow || t.hero.eyebrow}</div>
          <h1 className="hero__title">
            <span><i>{siteData?.heroTitleA || t.hero.titleA}</i></span>
            <span><i>{siteData?.heroTitleB || t.hero.titleB}</i></span>
            <span><i>{siteData?.heroTitleC || t.hero.titleC}</i></span>
          </h1>
        </div>
        <div className="hero__footer">
          <p className="hero__lede">{siteData?.heroLede || t.hero.lede}</p>
          <div className="hero__scroll">{t.hero.scroll}</div>
          <div className="hero__meta">
            <span><b>41°02′N</b>İstanbul</span>
            <span><b>28°59′E</b>Beyoğlu</span>
            <span><b>2023</b>Est.</span>
          </div>
        </div>
      </div>
    </section>);
}

function Marquee({ items }) {
  const content = <span>{items.map((it, i) => <React.Fragment key={i}>{it}</React.Fragment>).reduce((acc, el, i, arr) => { acc.push(el); if (i < arr.length - 1) acc.push(null); return acc; }, [])}</span>;
  return (
    <div className="marquee">
      <div className="marquee__track">
        {[...items, ...items, ...items, ...items].map((it, i) => <span key={i}>{it}</span>)}
      </div>
    </div>);
}

function Manifesto({ t, siteData }) {
  return (
    <section className="manifesto">
      <div className="section__label reveal">{t.manifesto.label}</div>
      <div className="manifesto__grid">
        <h2 className="manifesto__title reveal">
          <span className="ml">{siteData?.maniLine1 || t.manifesto.line1} <b>{siteData?.maniLine2 || t.manifesto.line2}</b></span>
          <span className="ml">{siteData?.maniLine3 || t.manifesto.line3} <b>{siteData?.maniLine4 || t.manifesto.line4}</b></span>
        </h2>
        <p className="manifesto__body reveal">{siteData?.maniBody || t.manifesto.body}</p>
      </div>
    </section>);
}

function About({ t, siteData }) {
  return (
    <section className="about" id="about">
      <div className="section__label reveal">{t.about.label}</div>
      <div className="about__grid">
        <div className="about__portrait reveal"><div className="about__initials">MS</div></div>
        <div>
          <h2 className="about__name reveal">{siteData?.aboutName || t.about.name}</h2>
          <div className="about__role reveal">{t.about.title}</div>
          <div className="about__bio">
            <p className="reveal">{siteData?.aboutBio1 || t.about.bio1}</p>
            <p className="reveal">{siteData?.aboutBio2 || t.about.bio2}</p>
          </div>
          <dl className="about__stats reveal">
            {t.about.stats.map((s, i) => <div key={i}><dt>{s.k}</dt><dd>{s.v}</dd></div>)}
          </dl>
        </div>
      </div>
    </section>);
}

function Practice({ t }) {
  return (
    <section className="section practice" id="practice">
      <div className="section__label reveal">{t.practice.label}</div>
      <div className="practice__head">
        <h2 className="heading reveal">{t.practice.heading}<br /><i>{t.practice.heading2}</i></h2>
      </div>
      <div className="practice__list">
        {t.practice.items.map((it) =>
        <div className="practice__row reveal" key={it.n}>
            <div className="practice__num">{it.n}</div>
            <h3 className="practice__title">{it.title}</h3>
            <div>
              <p className="practice__body">{it.body}</p>
              <div className="practice__tags">
                {it.tags.map((tag, i) => <span className="practice__tag" key={i}>{tag}</span>)}
              </div>
            </div>
            <div className="practice__arrow">→</div>
          </div>
        )}
      </div>
    </section>);
}

function Film({ t, siteData }) {
  const wrapRef = useRef(null);
  const videoRef = useRef(null);
  const fillRef = useRef(null);

  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    v.pause();
    let raf;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        if (!wrapRef.current || !v) return;
        const rect = wrapRef.current.getBoundingClientRect();
        const total = rect.height - window.innerHeight;
        const scrolled = Math.max(0, -rect.top);
        const p = Math.max(0, Math.min(1, scrolled / total));
        if (v.duration && !isNaN(v.duration)) { v.currentTime = p * v.duration; }
        if (fillRef.current) { fillRef.current.style.transform = `scaleX(${p})`; }
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    v.addEventListener("loadedmetadata", onScroll);
    onScroll();
    return () => { window.removeEventListener("scroll", onScroll); };
  }, []);

  useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    const handler = () => { if (v.readyState >= 2 && v.duration > 0) return; v.play().catch(() => {}); };
    const timeout = setTimeout(handler, 800);
    return () => clearTimeout(timeout);
  }, []);

  return (
    <section className="film" ref={wrapRef}>
      <div className="film__sticky">
        <video ref={videoRef} className="film__video" src="assets/hukuk.mp4" muted playsInline preload="auto" autoPlay loop />
        <div className="film__overlay" />
        <div className="film__content">
          <blockquote className="film__quote">
            <span style={{ display: "block" }}>{siteData?.maniLine1 || t.manifesto.line1} <b>{siteData?.maniLine2 || t.manifesto.line2}</b></span>
            <span style={{ display: "block" }}>{siteData?.maniLine3 || t.manifesto.line3} <b>{siteData?.maniLine4 || t.manifesto.line4}</b></span>
          </blockquote>
          <div className="film__cite">{t.manifesto.label} · Sözeri Law</div>
        </div>
        <div className="film__progress">
          <div className="film__progress-fill" ref={fillRef} />
        </div>
      </div>
    </section>);
}

function Approach({ t }) {
  return (
    <section className="approach" id="approach">
      <div className="section__label reveal">{t.approach.label}</div>
      <div className="approach__head">
        <h2 className="heading reveal">{t.approach.heading}<br /><i>{t.approach.heading2}</i></h2>
      </div>
      <div className="approach__steps">
        {t.approach.steps.map((s, i) =>
        <div className="approach__step reveal" key={i}>
            <div className="approach__num">{s.n}</div>
            <h3 className="approach__title">{s.title}</h3>
            <p className="approach__body">{s.body}</p>
          </div>
        )}
      </div>
    </section>);
}

function CTA({ t }) {
  return (
    <section className="cta" id="cta">
      <div className="cta__bordo" />
      <div className="cta__inner">
        <div className="section__label reveal" style={{ justifyContent: "center", display: "inline-flex" }}>{t.cta.label}</div>
        <h2 className="cta__title reveal">{t.cta.heading}<br /><i>{t.cta.heading2}</i></h2>
        <p className="cta__body reveal">{t.cta.body}</p>
        <div className="cta__buttons reveal">
          <a href="mailto:iletisim@sozerilaw.com" className="btn-primary"><span>{t.cta.button}</span><span>→</span></a>
          <a href="tel:+905307629964" className="btn-ghost">{t.cta.phone}</a>
        </div>
      </div>
    </section>);
}

function Contact({ t, siteData }) {
  return (
    <footer className="contact" id="contact">
      <div className="contact__grid">
        <div className="contact__mark reveal">
          <img src="assets/logo.png" alt="Sözeri Law" style={{ display: "block", marginRight: "auto", marginBottom: "20px", width: "250px", minWidth: "200px", height: "auto", objectFit: "contain" }} />
          <h4>Sözeri Avukatlık Ofisi</h4>
        </div>
        <div className="contact__block reveal">
          <h5>{t.contact.officeLabel}</h5>
          <p>{siteData?.contactOffice || t.contact.office}</p>
        </div>
        <div className="contact__block reveal">
          <h5>{t.contact.hoursLabel}</h5>
          <p>{siteData?.contactHours || t.contact.hours}</p>
        </div>
        <div className="contact__block reveal">
          <h5>{t.contact.emailLabel}</h5>
          <a href={`mailto:${siteData?.contactEmail || t.contact.email}`}>{siteData?.contactEmail || t.contact.email}</a>
        </div>
        <div className="contact__block reveal">
          <h5>{t.contact.webLabel}</h5>
          <a href="https://sozerilaw.com">{siteData?.contactPhone || t.contact.web}</a>
        </div>
      </div>
      <div className="footer">
        <p>{t.footer.disclaimer}</p>
        <p>© 2023—2026 Sözeri Law</p>
        <p className="footer__right">{t.footer.rights}{" · "}<a className="admin-link" href="admin.html">Admin</a></p>
      </div>
    </footer>);
}

function App() {
  const [lang, setLang] = useState(() => { return localStorage.getItem("sozeri_lang") || "tr"; });
  const [siteData, setSiteData] = useState({});
  const [appearance, setAppearance] = useState({});

  useEffect(() => {
    localStorage.setItem("sozeri_lang", lang);
    document.documentElement.lang = lang;

    if (window.SozeriApi && window.SozeriApi.getSettings) {
      window.SozeriApi.getSettings().then(res => {
        if (res) {
          setSiteData(res[`site_${lang}`] || {});
          setAppearance(res.appearance || {});
        }
      }).catch(err => console.error(err));
    }
  }, [lang]);

  const t = window.I18N[lang];
  useReveal();

  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    els.forEach((el) => el.classList.add("in"));
  }, [lang, siteData]);
useEffect(() => {
    if (window.location.hash) {
      setTimeout(() => {
        const element = document.querySelector(window.location.hash);
        if (element) {
          element.scrollIntoView({ behavior: 'smooth' });
        }
      }, 150);
    }
  }, []);
 return (
    <React.Fragment>
      {/* SİHİRLİ MOBİL DÜZELTME VE ÖZEL TASARIM KODU */}
      <style dangerouslySetInnerHTML={{__html: `
        /* Hamburger Butonu Ayarları */
        .hamburger { 
          display: none; 
          background: none; 
          border: none; 
          color: var(--cream); 
          font-size: 24px; 
          cursor: pointer; 
          padding: 5px 0 5px 15px; 
          margin-left: 10px; 
          border-left: 1px solid rgba(255,255,255,0.15); 
          z-index: 2001; 
        }

        @media (max-width: 768px) {
          .hamburger { display: block; }
          .nav__links { display: none; }
          
          /* MOBİL MENÜ ARKA PLANI - KOYU SAYDAM VE PUSLU */
          .nav__links--open {
            display: flex !important;
            flex-direction: column !important;
            position: fixed !important;
            top: 0;
            left: 0;
            width: 100%;
            height: 100vh;
            background: rgba(0, 0, 0, 0.0) !important; /* İstediğin o koyu ama saydam siyahlık */
            backdrop-filter: blur(15px) !important; /* Arkadaki içeriği harika şekilde puslu yapar */
            padding: 120px 20px 40px 20px !important;
            gap: 25px !important;
            align-items: center;
            z-index: 2000 !important;
          }

          /* Mobil Linkler - Dil Fontuyla Aynı (Small & Mono) */
          .nav__links--open a {
            font-family: var(--mono) !important;
            font-size: 13px !important;
            text-transform: uppercase !important;
            letter-spacing: 0.2em !important;
            color: var(--cream) !important;
            text-decoration: none;
            opacity: 0.8;
          }

          .nav__links--open a:active { opacity: 1; color: var(--bordo); }

          /* Sıkışan Uzmanlık Alanları Düzeltmesi */
          .practice__row { display: flex !important; flex-direction: column !important; gap: 16px; }
          .practice__row > div, .practice__row > h3 { width: 100% !important; }
          
          /* Mobil Buton Gizleme */
          .hide-on-mobile { display: none !important; }
        }
      `}} />

      <div className="loader"><div className="loader__bar" /></div>
      <Nav lang={lang} setLang={setLang} t={t} appearance={appearance} />
      <Hero t={t} siteData={siteData} />
      <Marquee items={t.marquee} />
      <Manifesto t={t} siteData={siteData} />
      <About t={t} siteData={siteData} />
      <Practice t={t} />
      <Film t={t} siteData={siteData} />
      <Approach t={t} />
      <CTA t={t} />
      <Contact t={t} siteData={siteData} />
    </React.Fragment>
  );
}

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