/* page-components.jsx — shared inner-page shell: PageHero, PricingCard, FAQ, etc. */

/* ---------- Inner-page hero (mini header below nav) ---------- */
function PageHero({ eyebrow, title, titleAccent, sub, bg }) {
  return (
    <div className="hero-wrap" style={{ minHeight: 'auto' }}>
      <section className={"hero-card" + (bg === 'deep' ? ' deep' : '')}
               style={{ height: 'auto', minHeight: '360px', padding: '0', justifyContent: 'flex-end' }}>
        <div className="aurora">
          <span className="blob b1" /><span className="blob b2" /><span className="blob b3" />
          <span className="grain" />
        </div>
        <div className="hero-inner" style={{ justifyContent: 'center', padding: '4rem 1.5rem 3.5rem' }}>
          <div className="hero-text" style={{ paddingTop: 0 }}>
            {eyebrow && (
              <div className="badge anim d1">
                <Sparkles />
                <span>{eyebrow}</span>
              </div>
            )}
            <h1 className="hero-h1 anim d2">
              {title}
              {titleAccent && <><br /><span className="accent">{titleAccent}</span></>}
            </h1>
            {sub && <p className="hero-sub anim d3">{sub}</p>}
          </div>
        </div>
      </section>
    </div>
  );
}

/* ---------- Pricing card ---------- */
function PricingCard({ plan, ru }) {
  const { name, price, period, highlight, specs, cta, ctaHref } = plan;
  return (
    <div className={"glass-card" + (highlight ? ' pricing-highlight' : '')}
         style={{ display: 'flex', flexDirection: 'column', gap: 0, padding: 0 }}>
      <span className="glow" />
      <div style={{ padding: '1.8rem 1.8rem 0' }}>
        {highlight && (
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: '0.4rem',
                        background: 'var(--brand)', color: '#fff', borderRadius: '999px',
                        padding: '0.25rem 0.8rem', fontSize: '0.75rem', fontWeight: 700,
                        letterSpacing: '0.06em', marginBottom: '1rem' }}>
            <Sparkles style={{ width: 13, height: 13 }} />
            {ru ? 'Популярный' : 'Popular'}
          </div>
        )}
        <div style={{ fontSize: '1.1rem', fontWeight: 700, color: 'rgba(var(--brand-deep),0.95)', marginBottom: '0.5rem' }}>{name}</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: '0.3rem', marginBottom: '1.4rem' }}>
          <span style={{ fontSize: '2.4rem', fontWeight: 800, letterSpacing: '-0.04em', color: 'var(--brand)', lineHeight: 1 }}>{price}</span>
          <span style={{ fontSize: '0.88rem', color: 'var(--muted)', fontWeight: 500 }}>{period}</span>
        </div>
        <ul className="svc-specs" style={{ marginBottom: '1.6rem' }}>
          {specs.map((s, i) => <li key={i}><Check /> {s}</li>)}
        </ul>
      </div>
      <div style={{ marginTop: 'auto', padding: '1.2rem 1.8rem', borderTop: '1px solid rgba(var(--brand-deep),0.08)' }}>
        <a href={ctaHref || '#'} className={"btn" + (highlight ? ' btn-primary' : ' btn-ghost')}
           style={{ width: '100%', justifyContent: 'center' }}>
          {cta}<ArrowRight />
        </a>
      </div>
    </div>
  );
}

/* ---------- Live catalog plans (real tariffs from /api/plans) ---------- */
function CatalogPlans({ category, ru, fallback }) {
  const [plans, setPlans] = React.useState(null);
  React.useEffect(() => {
    fetch('/api/plans?category=' + encodeURIComponent(category), { credentials: 'same-origin' })
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => setPlans(d && Array.isArray(d.plans) ? d.plans : []))
      .catch(() => setPlans([]));
  }, [category]);

  const rub = (n) => new Intl.NumberFormat('ru-RU').format(Math.round(Number(n || 0))) + ' ₽';

  // loading
  if (plans === null) {
    return (
      <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: '1rem' }}>
        {[0, 1, 2].map((i) => (
          <div key={i} className="glass-card" style={{ minHeight: 280, opacity: 0.5 }}>
            <span className="glow" />
          </div>
        ))}
      </div>
    );
  }

  // map live plans → PricingCard format; fall back to static plans if catalog empty
  let list;
  if (plans.length) {
    const grouped = {};
    plans.forEach((p) => {
      const g = p.group || '';
      (grouped[g] = grouped[g] || []).push(p);
    });
    const groups = Object.keys(grouped);
    const hasGroups = groups.length > 1;
    // pick the largest group as primary so the page isn't overwhelming
    const primary = hasGroups
      ? groups.sort((a, b) => grouped[b].length - grouped[a].length)[0]
      : groups[0];
    const src = (grouped[primary] || plans).slice().sort((a, b) => Number(a.price) - Number(b.price));
    list = src.map((p) => ({
      name: p.name,
      price: rub(p.price),
      period: ru ? '/мес' : '/mo',
      highlight: !!p.popular,
      specs: (p.specs && p.specs.length ? p.specs : [p.description].filter(Boolean)).slice(0, 6),
      cta: ru ? 'Заказать' : 'Order',
      ctaHref: '/cabinet',
    }));
  } else {
    list = fallback || [];
  }

  if (!list.length) {
    return (
      <div className="glass-card" style={{ padding: '2rem', textAlign: 'center', color: 'var(--muted)' }}>
        {ru ? 'Тарифы скоро появятся.' : 'Plans coming soon.'}
      </div>
    );
  }

  return (
    <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: '1rem' }}>
      {list.map((p, i) => (
        <div className="reveal" key={i} style={{ transitionDelay: `${i * 50}ms` }}>
          <PricingCard plan={p} ru={ru} />
        </div>
      ))}
    </div>
  );
}

/* ---------- FAQ accordion ---------- */
function FAQ({ items }) {
  const [open, setOpen] = React.useState(null);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
      {items.map((item, i) => (
        <div key={i} className="glass-card" style={{ padding: '1.2rem 1.6rem', cursor: 'pointer', transition: 'all 0.2s' }}
             onClick={() => setOpen(open === i ? null : i)}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '1rem' }}>
            <span style={{ fontWeight: 600, fontSize: '1rem', color: 'rgba(var(--brand-deep),0.95)' }}>{item.q}</span>
            <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'rgba(var(--brand-rgb),0.1)',
                          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                          transform: open === i ? 'rotate(90deg)' : 'none', transition: 'transform 0.2s' }}>
              <ChevronRight style={{ width: 16, height: 16, color: 'var(--brand)' }} />
            </div>
          </div>
          {open === i && (
            <p style={{ margin: '0.8rem 0 0', fontSize: '0.96rem', color: 'var(--muted)', lineHeight: 1.6 }}>{item.a}</p>
          )}
        </div>
      ))}
    </div>
  );
}

/* ---------- Spec table ---------- */
function SpecTable({ rows }) {
  return (
    <div className="glass-card" style={{ padding: 0, overflow: 'hidden' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <tbody>
          {rows.map((r, i) => (
            <tr key={i} style={{ borderBottom: i < rows.length - 1 ? '1px solid rgba(var(--brand-deep),0.07)' : 'none' }}>
              <td style={{ padding: '0.9rem 1.6rem', fontWeight: 600, color: 'rgba(var(--brand-deep),0.7)', fontSize: '0.88rem', width: '38%' }}>{r[0]}</td>
              <td style={{ padding: '0.9rem 1.6rem', color: 'rgba(var(--brand-deep),0.92)', fontSize: '0.96rem' }}>{r[1]}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

/* ---------- Legal page body ---------- */
function LegalBody({ sections }) {
  return (
    <div style={{ maxWidth: '760px', margin: '0 auto' }}>
      {sections.map((s, i) => (
        <div key={i} style={{ marginBottom: '2.5rem' }} className="reveal">
          {s.h && <h2 style={{ fontSize: '1.35rem', fontWeight: 700, color: 'rgba(var(--brand-deep),0.95)', marginBottom: '0.8rem', letterSpacing: '-0.02em' }}>{s.h}</h2>}
          {s.p && <p style={{ fontSize: '1rem', lineHeight: 1.7, color: 'var(--muted)', margin: 0 }}>{s.p}</p>}
          {s.list && (
            <ul style={{ margin: '0.8rem 0 0', padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              {s.list.map((li, j) => (
                <li key={j} style={{ display: 'flex', gap: '0.6rem', alignItems: 'flex-start', fontSize: '0.98rem', color: 'var(--muted)', lineHeight: 1.6 }}>
                  <Check style={{ width: 16, height: 16, color: 'var(--brand)', flexShrink: 0, marginTop: '0.2rem' }} />
                  {li}
                </li>
              ))}
            </ul>
          )}
        </div>
      ))}
    </div>
  );
}

/* ---------- Inner-page sticky navbar ---------- */
function StickyNav({ t, lang, setLang }) {
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 100,
      background: 'rgba(233,237,243,0.82)',
      backdropFilter: 'blur(22px)', WebkitBackdropFilter: 'blur(22px)',
      borderBottom: '1px solid rgba(47,89,214,0.07)',
    }}>
      <Navbar t={t} lang={lang} setLang={setLang} />
    </div>
  );
}

/* ---------- Inner-page app wrapper ---------- */
function PageApp({ children, title }) {
  const [lang, setLang] = React.useState(() => localStorage.getItem('hl_lang') || 'ru');
  const t = I18N[lang];
  const revealRef = useReveal();

  React.useEffect(() => { localStorage.setItem('hl_lang', lang); }, [lang]);
  React.useEffect(() => {
    const id = setTimeout(() => document.documentElement.classList.add('anims-finished'), 300);
    return () => clearTimeout(id);
  }, []);

  return (
    <div className="page" ref={revealRef}>
      <StickyNav t={t} lang={lang} setLang={setLang} />
      {typeof children === 'function' ? children({ t, lang }) : children}
      <CTA t={t} />
      <SiteFooter t={t} />
    </div>
  );
}

Object.assign(window, { PageHero, PricingCard, FAQ, SpecTable, LegalBody, PageApp });
