// Yookie Pro (business) landing — nav, hero, promo, value grid, for-whom, steps + mount.
const { useState, useEffect, useRef } = React;
const { useTweaks, TweaksPanel, TweakSection, TweakColor } = window;
const B = window.YookieBiz;
const { ConfirmToast, TimeChip } = window.YookieFragments;
const BI18N = window.YookieBizI18n;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{ "accent": "#76D099" }/*EDITMODE-END*/;

// ── language persistence ──
function useLang() {
  const [lang, setLang] = useState(() => {
    try { const s = localStorage.getItem("yookie_lang"); if (s && BI18N[s]) return s; } catch (e) {}
    return "ru";
  });
  useEffect(() => {
    try { localStorage.setItem("yookie_lang", lang); } catch (e) {}
    document.documentElement.lang = lang;
  }, [lang]);
  return [lang, setLang];
}

function scrollToId(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const headH = parseInt(getComputedStyle(document.documentElement).getPropertyValue("--biz-top-h"), 10) || 80;
  window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - headH - 16, behavior: "smooth" });
}

// ── Lang selector ──
function LangSelector({ lang, setLang, up }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", onClick);
    return () => document.removeEventListener("mousedown", onClick);
  }, []);
  const langs = [{ c: "ru", l: "Русский", s: "RU" }, { c: "uz", l: "O‘zbekcha", s: "UZ" }, { c: "en", l: "English", s: "EN" }];
  const cur = langs.find(l => l.c === lang) || langs[0];
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button className="lang-btn" onClick={() => setOpen(o => !o)}>
        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 010 18M12 3a14 14 0 000 18"/></svg>
        {cur.s}
        <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M6 9l6 6 6-6"/></svg>
      </button>
      {open && (
        <div className="lang-pop" style={up ? { top: "auto", bottom: "calc(100% + 8px)" } : null}>
          {langs.map(l =>
            <button key={l.c} onClick={() => { setLang(l.c); setOpen(false); }} className={lang === l.c ? "active" : ""}>
              <span>{l.l}</span><span style={{ fontSize: 11, opacity: 0.5, fontWeight: 700 }}>{l.s}</span>
            </button>
          )}
        </div>
      )}
    </div>
  );
}

// ── Nav ──
function Nav({ t, lang, setLang }) {
  return (
    <div className="nav-wrap">
      <nav className="nav">
        <a href="business.html" style={{ display: "inline-flex", alignItems: "center", gap: 8, textDecoration: "none", marginRight: 6 }}>
          <span className="logo-grad" role="img" aria-label="Yookie" style={{ height: 21, width: 63, display: "block" }} />
          <span className="pro-badge">Pro</span>
        </a>
        <a className="navlink" href="#value" onClick={(e) => { e.preventDefault(); scrollToId("value"); }}>{t.nav.value}</a>
        <a className="navlink" href="#whom" onClick={(e) => { e.preventDefault(); scrollToId("whom"); }}>{t.nav.whom}</a>
        <a className="navlink" href="#pricing" onClick={(e) => { e.preventDefault(); scrollToId("pricing"); }}>{t.nav.pricing}</a>
        <a className="navlink" href="#faq" onClick={(e) => { e.preventDefault(); scrollToId("faq"); }}>{t.nav.faq}</a>
        <div style={{ width: 1, height: 22, background: "var(--line)", margin: "0 2px" }} className="hide-mobile" />
        <LangSelector lang={lang} setLang={setLang} />
        <a className="navlink hide-mobile" href={B.CLIENT_URL} style={{ fontWeight: 600 }}>{t.nav.client}</a>
        <a className="btn btn-primary" href={B.AUTH} data-cta="hero" target="_blank" rel="noopener noreferrer" style={{ height: 40, padding: "0 18px", fontSize: 13.5 }}>{t.nav.cta}</a>
      </nav>
    </div>
  );
}

// ── Promo strip ──
function Promo({ t }) {
  return (
    <div className="promo">
      <a className="promo-inner" href="#bonus" onClick={(e) => { e.preventDefault(); scrollToId("bonus"); }}>
        <span className="promo-dot" />
        <span><b>{t.promo.a}</b>{t.promo.b}<span className="g">{t.promo.c}</span>{t.promo.d}</span>
      </a>
    </div>
  );
}

// ── Hero dashboard mock ──
function BizDashboard({ t }) {
  const rows = [
    { ti: "10:00", n: "Madina K.", s: "Маникюр", st: "active" },
    { ti: "11:30", n: "Студия йоги", s: "Группа · 8 мест", st: "ok" },
    { ti: "13:00", n: "Анна И.", s: "Окрашивание", st: "ok" },
    { ti: "15:00", n: "Bekzod T.", s: "Барбершоп", st: "ok" }
  ];
  const bars = [40, 62, 48, 80, 95, 70, 88];
  return (
    <div style={{ position: "relative" }}>
      <div style={{ background: "#fff", border: "1px solid var(--line)", borderRadius: 24, padding: 22, boxShadow: "0 44px 90px -40px rgba(20,70,160,0.4), 0 2px 10px rgba(20,70,160,0.06)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
          <div>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>Сегодня · 28 апреля</div>
            <div style={{ fontSize: 26, fontWeight: 700, letterSpacing: -0.6, marginTop: 2 }}>4 250 000 <span style={{ fontSize: 14, color: "var(--ink-3)" }}>сум</span></div>
          </div>
          <span style={{ fontSize: 11.5, fontWeight: 700, padding: "5px 10px", borderRadius: 999, background: "color-mix(in srgb, var(--green) 16%, transparent)", color: "#2a8a18" }}>+ 24%</span>
        </div>
        <div style={{ display: "flex", alignItems: "flex-end", gap: 7, height: 64, padding: "0 2px 0", marginBottom: 18 }}>
          {bars.map((b, i) =>
            <div key={i} style={{ flex: 1, height: `${b}%`, borderRadius: 6, background: i === 4 ? "var(--ac)" : "var(--ac-soft)" }} />
          )}
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          {rows.map((r, i) =>
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "9px 12px", borderRadius: 12, background: r.st === "active" ? "var(--ac-soft)" : "var(--bg)", border: r.st === "active" ? "1px solid var(--ac-line)" : "1px solid var(--line-soft)" }}>
              <div style={{ fontSize: 12.5, fontWeight: 700, color: r.st === "active" ? "var(--ac)" : "var(--ink)", width: 40 }}>{r.ti}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{r.n}</div>
                <div style={{ fontSize: 11, color: "var(--ink-3)" }}>{r.s}</div>
              </div>
              {r.st === "active" && <span style={{ fontSize: 10, fontWeight: 700, color: "var(--ac)", padding: "3px 7px", borderRadius: 6, background: "#fff" }}>сейчас</span>}
            </div>
          )}
        </div>
      </div>
      <div style={{ position: "absolute", top: -18, right: -14, animation: "bobA 4s ease-in-out infinite" }}><ConfirmToast delay={0} /></div>
    </div>
  );
}

// ── Hero ──
function Hero({ t }) {
  const isMobile = B.useIsMobileB();
  return (
    <section style={{ paddingTop: isMobile ? 48 : 64, paddingLeft: isMobile ? 18 : 24, paddingRight: isMobile ? 18 : 24, paddingBottom: isMobile ? 30 : 40 }}>
      <div className="wrap" style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1.05fr 0.95fr", gap: isMobile ? 44 : 56, alignItems: "center" }}>
        <div>
          <span className="pro-badge" style={{ fontSize: 12.5, padding: "6px 12px" }}>{t.hero.badge}</span>
          <h1 style={{ fontFamily: "'Gilroy', sans-serif", fontSize: isMobile ? "clamp(40px, 11vw, 60px)" : "clamp(48px, 5.4vw, 86px)", lineHeight: 0.97, letterSpacing: isMobile ? -2 : -3, margin: "18px 0 0", fontWeight: 600, color: "var(--ink)", textWrap: "balance" }}>
            {t.hero.l1} <span className="script">{t.hero.l2}</span>
          </h1>
          <p className="lede">{t.hero.sub}</p>
          <div style={{ display: "flex", gap: 12, marginTop: 30, flexWrap: "wrap" }}>
            <a className="btn btn-primary" href={B.AUTH} data-cta="hero" target="_blank" rel="noopener noreferrer"><B.TgIcon size={16} color="#fff" />{t.hero.cta1}</a>
            <a className="btn btn-ghost" href="#pricing" onClick={(e) => { e.preventDefault(); scrollToId("pricing"); }}>{t.hero.cta2}</a>
          </div>
        </div>
        <BizDashboard t={t} />
      </div>
    </section>
  );
}

// ── Value grid ──
function ValueGrid({ t }) {
  const [ref, inView] = B.useReveal();
  const icons = ["bell", "calendar", "chart", "users", "box", "gift"];
  return (
    <section id="value" className="sec-pad" ref={ref}>
      <div className="wrap">
        <div className={`reveal ${inView ? "in" : ""}`}>
          <p className="kicker ac">{t.value.kicker}</p>
          <h2 className="title">{t.value.titleA} <span className="script" style={{ whiteSpace: "nowrap" }}>{t.value.titleB}</span></h2>
        </div>
        <div className={`biz-grid stagger ${inView ? "in" : ""}`}>
          {t.value.cards.map((c, i) =>
            <div key={i} className="biz-card">
              <div className="biz-ico"><B.Icon name={icons[i]} size={24} /></div>
              <h3>{c.t}</h3>
              <p>{c.d}</p>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

// ── For whom ──
function ForWhom({ t }) {
  const [ref, inView] = B.useReveal();
  const icons = ["scissors", "activity", "leaf", "book", "user", "grid"];
  return (
    <section id="whom" className="sec-pad" ref={ref}>
      <div className="wrap">
        <div className={`reveal ${inView ? "in" : ""}`}>
          <p className="kicker">{t.whom.kicker}</p>
          <h2 className="title">{t.whom.titleA} <span className="script">{t.whom.titleB}</span></h2>
          <p className="lede">{t.whom.sub}</p>
        </div>
        <div className={`whom-grid stagger ${inView ? "in" : ""}`}>
          {t.whom.items.map((w, i) =>
            <div key={i} className="whom-card">
              <span className="whom-ico"><B.Icon name={icons[i]} size={22} /></span>
              <div><h3>{w.t}</h3><p>{w.d}</p></div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

// ── How to start ──
function HowStart({ t }) {
  const [ref, inView] = B.useReveal();
  return (
    <section id="start" className="sec-pad" ref={ref}>
      <div className="wrap">
        <div className={`reveal ${inView ? "in" : ""}`}>
          <p className="kicker">{t.start.kicker}</p>
          <h2 className="title">{t.start.titleA} <span className="script">{t.start.titleB}</span></h2>
        </div>
        <div className={`steps4 stagger ${inView ? "in" : ""}`}>
          {t.start.steps.map((s, i) =>
            <div key={i} className="step4">
              <div className="n"><i />ШАГ 0{i + 1}</div>
              <h3>{s.t}</h3>
              <p>{s.d}</p>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

// ── App ──
function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = useLang();
  const t = BI18N[lang];

  useEffect(() => {
    const loader = document.getElementById("page-loader");
    if (!loader) return;
    loader.style.opacity = "0";
    const tm = setTimeout(() => loader.remove(), 280);
    return () => clearTimeout(tm);
  }, []);

  useEffect(() => { document.documentElement.style.setProperty("--ac", tweaks.accent); }, [tweaks]);

  // Measure the sticky nav pill so anchor scrolling lands below it once it's
  // stuck to the top — height varies a touch with font/zoom.
  useEffect(() => {
    const el = document.querySelector(".nav-wrap");
    if (!el) return;
    const set = () => document.documentElement.style.setProperty("--biz-top-h", el.offsetHeight + "px");
    set();
    window.addEventListener("resize", set);
    const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(set) : null;
    if (ro) ro.observe(el);
    return () => { window.removeEventListener("resize", set); if (ro) ro.disconnect(); };
  }, []);

  const presets = [
    { v: "#76D099", l: "Brand" },
    { v: "#9CEF39", l: "Green" },
    { v: "#50B2F9", l: "Sky" },
    { v: "#2F8BE8", l: "Deep" },
    { v: "#7A5BFF", l: "Violet" }
  ];

  return (
    <div>
      <Promo t={t} />
      <Nav t={t} lang={lang} setLang={setLang} />
      <main>
        <Hero t={t} />
        <ValueGrid t={t} />
        <ForWhom t={t} />
        <HowStart t={t} />
        <B.Pricing t={t} />
        <B.BonusBlock t={t} />
        <B.FAQ t={t} />
        <B.BizFinalCTA t={t} />
        <B.BizFooter t={t} LangInline={<div style={{ marginTop: 4 }}><LangSelector lang={lang} setLang={setLang} up /></div>} />
      </main>

      <TweaksPanel title={t.tweaks.title} defaultPos={{ right: 20, bottom: 20 }}>
        <TweakSection title={t.tweaks.accent}>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            {presets.map((p) =>
              <button key={p.v} onClick={() => setTweak("accent", p.v)} style={{ width: 36, height: 36, borderRadius: 10, border: tweaks.accent === p.v ? "2px solid var(--ink)" : "2px solid transparent", background: p.v, cursor: "pointer", padding: 2 }} title={p.l} />
            )}
          </div>
          <TweakColor label={t.tweaks.custom} value={tweaks.accent} onChange={(v) => setTweak("accent", v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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