const { useState: uS, useEffect: uE, useRef: uR } = React;

// ---------- NAVBAR ----------
function Navbar({ onCta }) {
  const [scrolled, setScrolled] = uS(false);
  const { lang, setLang, t } = useLang();
  const { theme, setTheme } = useTheme();
  const dark = theme !== 'light';
  uE(() => {
    const onS = () => setScrolled(window.scrollY > 24);
    onS();
    window.addEventListener('scroll', onS);
    return () => window.removeEventListener('scroll', onS);
  }, []);
  const headerBg = dark
    ? (scrolled ? 'rgba(6,6,11,0.65)' : 'rgba(6,6,11,0.25)')
    : (scrolled ? 'rgba(255,255,255,0.78)' : 'rgba(255,255,255,0.45)');
  return (
    <header className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300`} style={{
      paddingTop: scrolled ? 10 : 18,
      paddingBottom: scrolled ? 10 : 18,
      backdropFilter: scrolled ? 'blur(22px) saturate(160%)' : 'blur(8px) saturate(120%)',
      WebkitBackdropFilter: scrolled ? 'blur(22px) saturate(160%)' : 'blur(8px) saturate(120%)',
      background: headerBg,
      borderBottom: scrolled ? `1px solid ${dark ? 'rgba(255,255,255,0.06)' : 'rgba(10,15,30,0.08)'}` : '1px solid transparent',
    }}>
      <div className="mx-auto max-w-7xl px-6 md:px-10 flex items-center justify-between gap-6">
        <a href="#home" className="flex items-center gap-2.5 pulse-logo rounded-md px-1" data-hot>
          <span className="relative inline-flex items-center justify-center w-7 h-7 rounded-md" style={{
            background: 'linear-gradient(135deg, #00F0FF, #8B5CF6)',
            boxShadow: '0 0 16px rgba(0,240,255,0.45)',
          }}>
            <span className="text-black font-display font-bold text-[15px]">H</span>
          </span>
          <span className="font-display text-lg font-semibold tracking-tight text-white">Hunara<span className="text-cyan1">AI</span></span>
        </a>

        <nav className="hidden lg:flex items-center gap-8 text-sm text-white/70">
          {[['nav_home','#home'],['nav_how','#how'],['nav_team','#team'],['nav_industries','#industries'],['nav_about','#why']].map(([k,h]) => (
            <a key={k} href={h} className="hover:text-white transition-colors relative group" data-hot>
              {t(k)}
              <span className="absolute left-0 -bottom-1.5 w-0 h-px bg-cyan1 group-hover:w-full transition-all"></span>
            </a>
          ))}
        </nav>

        <div className="flex items-center gap-2 md:gap-3">
          <div className="relative hidden sm:block">
            <select value={lang} onChange={(e)=>setLang(e.target.value)} className="appearance-none bg-white/[0.04] border border-white/10 rounded-lg pl-3 pr-7 py-1.5 mono text-[11px] tracking-widest text-white/70 hover:border-white/20 cursor-pointer" data-hot>
              <option value="EN">EN</option>
              <option value="HI">हिंदी</option>
              <option value="GU">ગુજરાતી</option>
            </select>
            <svg className="absolute right-1.5 top-1/2 -translate-y-1/2 w-3 h-3 text-white/50 pointer-events-none" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="6 9 12 15 18 9"/></svg>
          </div>
          <button onClick={()=>setTheme(dark ? 'light' : 'dark')} className="w-9 h-9 rounded-lg bg-white/[0.04] border border-white/10 flex items-center justify-center text-white/70 hover:text-white hover:border-white/20" data-hot aria-label="Toggle theme">
            {dark ? (
              <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"/></svg>
            ) : (
              <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"/></svg>
            )}
          </button>
          <a href="https://app.hunaraai.io/login" className="hidden sm:inline-flex items-center px-3 md:px-4 py-2 rounded-lg text-sm text-white/80 hover:text-white border border-white/10 hover:border-white/20 bg-white/[0.03] hover:bg-white/[0.06] transition-colors" data-hot>
            {t('nav_login')}
          </a>
          <Magnetic className="btn-primary px-4 md:px-5 py-2 rounded-lg text-sm font-medium glow-border" as="a" href="#demo">
            {t('nav_demo')}
          </Magnetic>
        </div>
      </div>
    </header>
  );
}

// ---------- HOW IT WORKS ----------
function HowItWorks() {
  const { t } = useLang();
  const steps = [
    { icon: '📞', title: t('how_s1_t'), desc: t('how_s1_d') },
    { icon: '🤖', title: t('how_s2_t'), desc: t('how_s2_d') },
    { icon: '✅', title: t('how_s3_t'), desc: t('how_s3_d') },
    { icon: '📊', title: t('how_s4_t'), desc: t('how_s4_d') },
  ];
  return (
    <section id="how" data-screen-label="03 How It Works" className="relative py-24 md:py-32">
      <div className="mx-auto max-w-7xl px-6 md:px-10">
        <SectionHeader
          tag={t('how_tag')}
          title={t('how_title')}
          subtitle={t('how_sub')}
        />
        <div className="relative">
          <div className="hidden md:block absolute top-16 left-0 right-0 h-px" style={{
            background: 'linear-gradient(90deg, transparent, rgba(0,240,255,0.4), rgba(139,92,246,0.4), rgba(255,184,0,0.4), transparent)',
          }}></div>
          <div className="grid md:grid-cols-4 gap-5 reveal">
            {steps.map((s, i) => (
              <div key={i} className="relative" style={{ transitionDelay: `${i * 100}ms` }}>
                <div className="hidden md:flex items-center justify-center w-10 h-10 rounded-full mx-auto mb-6 relative" style={{
                  background: 'rgba(6,6,11,1)',
                  border: '1px solid rgba(0,240,255,0.4)',
                  boxShadow: '0 0 20px rgba(0,240,255,0.25)',
                }}>
                  <span className="mono text-xs text-cyan1">0{i+1}</span>
                  <span className="absolute inset-0 rounded-full" style={{
                    border: '1px solid rgba(0,240,255,0.3)',
                    animation: `pulseGlow 3s ease-in-out infinite ${i*0.4}s`,
                  }}></span>
                </div>
                <Tilt max={6} scale={1.02}>
                  <div className="glass rounded-2xl p-6 h-full">
                    <div className="text-3xl mb-4">{s.icon}</div>
                    <div className="text-lg font-display font-semibold text-white mb-2">{s.title}</div>
                    <p className="text-sm text-white/60 leading-relaxed">{s.desc}</p>
                  </div>
                </Tilt>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- INDUSTRIES ----------
function IndustryCard({ ind }) {
  const { t } = useLang();
  const [open, setOpen] = uS(false);
  return (
    <Tilt max={10} scale={1.03}>
      <div className="glass rounded-2xl p-6 h-full flex flex-col" style={{ minHeight: 200 }}>
        <div className="flex items-start justify-between mb-3">
          <div className="text-4xl transition-transform" style={{ transform: 'scale(1)' }}>{ind.icon}</div>
          <button data-hot onClick={()=>setOpen(!open)} className="mono text-[10px] tracking-widest text-white/40 hover:text-cyan1 transition-colors">
            {open ? t('ind_close') : t('ind_details')}
          </button>
        </div>
        <h3 className="text-xl font-display font-semibold text-white">{t(ind.tKey)}</h3>
        <p className="text-sm text-white/55 mt-2">{t(ind.sKey)}</p>
        <div className="overflow-hidden transition-all duration-500" style={{ maxHeight: open ? 280 : 0, opacity: open ? 1 : 0 }}>
          <div className="hairline my-4"></div>
          <p className="text-sm text-white/70 leading-relaxed">{t(ind.lKey)}</p>
        </div>
      </div>
    </Tilt>
  );
}

function IndustriesSection() {
  const { t } = useLang();
  return (
    <section id="industries" data-screen-label="05 Industries" className="relative py-24 md:py-32">
      <div className="mx-auto max-w-7xl px-6 md:px-10">
        <SectionHeader
          tag={t('ind_tag')}
          title={t('ind_title')}
          subtitle={t('ind_sub')}
        />
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5 reveal">
          {INDUSTRIES.map((ind) => <IndustryCard key={ind.tKey} ind={ind} />)}
        </div>
        <div className="mt-12 reveal flex flex-col sm:flex-row items-center justify-between gap-5 glass rounded-2xl p-6 md:p-7">
          <div>
            <div className="text-lg font-display font-semibold text-white">{t('ind_cta_t')}</div>
            <div className="text-sm text-white/55">{t('ind_cta_d')}</div>
          </div>
          <Magnetic as="a" href="#demo" className="btn-primary px-5 py-3 rounded-lg text-sm font-medium">
            {t('ind_cta_btn')}
          </Magnetic>
        </div>
      </div>
    </section>
  );
}

// ---------- WHY HUNARA ----------
function WhySection() {
  const { t } = useLang();
  const items = [
    { icon: '🕒', title: t('why_1_t'), desc: t('why_1_d'), metric: 100, suffix: '%', accent: '#00F0FF' },
    { icon: '📉', title: t('why_2_t'), desc: t('why_2_d'), metric: 78, suffix: '%', metricLabel: t('why_2_lbl'), accent: '#FFB800' },
    { icon: '📈', title: t('why_3_t'), desc: t('why_3_d'), metric: 3, suffix: 'x', metricLabel: t('why_3_lbl'), accent: '#8B5CF6' },
    { icon: '⚡', title: t('why_4_t'), desc: t('why_4_d'), metric: 10000, suffix: '+', metricLabel: t('why_4_lbl'), accent: '#34D399' },
  ];
  return (
    <section id="why" data-screen-label="06 Why" className="relative py-24 md:py-32">
      <div className="mx-auto max-w-7xl px-6 md:px-10">
        <SectionHeader
          tag={t('why_tag')}
          title={t('why_title')}
          subtitle={t('why_sub')}
        />
        <div className="grid md:grid-cols-2 gap-5 reveal">
          {items.map((it, i) => (
            <Tilt key={i} max={8} scale={1.02}>
              <div className="glass-strong rounded-2xl p-7 md:p-8 h-full relative overflow-hidden" style={{ minHeight: 230 }}>
                <div className="absolute -top-20 -right-20 w-56 h-56 rounded-full opacity-50" style={{
                  background: `radial-gradient(circle, ${it.accent}33, transparent 60%)`,
                }}></div>
                <div className="flex items-start justify-between relative z-10">
                  <div className="text-3xl">{it.icon}</div>
                  <div className="text-right">
                    <div className="text-3xl md:text-4xl font-display font-semibold" style={{ color: it.accent, textShadow: `0 0 24px ${it.accent}55` }}>
                      <Counter value={it.metric} suffix={it.suffix} />
                    </div>
                    {it.metricLabel && <div className="mono text-[10px] tracking-widest text-white/40 mt-1">{it.metricLabel}</div>}
                  </div>
                </div>
                <h3 className="text-xl font-display font-semibold text-white mt-6 relative z-10">{it.title}</h3>
                <p className="text-sm text-white/60 mt-2 relative z-10 leading-relaxed">{it.desc}</p>
              </div>
            </Tilt>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- DEMO FORM ----------
function DemoSection() {
  const { t } = useLang();
  const [form, setForm] = uS({ name: '', phone: '', company: '', city: '', industry: 'Ceramic & Tiles' });
  const [submitted, setSubmitted] = uS(false);
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const submit = async (e) => {
    e.preventDefault();
    try {
      await fetch('https://api.hunaraai.io/api/website/demo-request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: form.name,
          phone: '+91' + form.phone.replace(/\s/g, ''),
          company: form.company,
          city: form.city,
          industry: form.industry,
          source: 'website'
        })
      });
      setSubmitted(true);
    } catch (err) {
      console.error('Demo request failed:', err);
      setSubmitted(true); // show success anyway — don't lose the lead
    }
  };
  return (
    <section id="demo" data-screen-label="07 Demo" className="relative py-24 md:py-32">
      <div className="mx-auto max-w-5xl px-6 md:px-10">
        <SectionHeader
          tag={t('demo_tag')}
          title={t('demo_title')}
          subtitle={t('demo_sub')}
          align="center"
        />
        <div className="reveal glow-border rounded-3xl">
          <div className="glass-strong rounded-3xl p-7 md:p-10">
            {submitted ? (
              <div className="text-center py-12">
                <div className="text-5xl mb-5">✅</div>
                <div className="text-2xl font-display font-semibold text-white">{t('demo_success_t')} {form.name || t('demo_success_friend')}.</div>
                <div className="text-white/60 mt-3 max-w-md mx-auto">{t('demo_success_d_pre')} {form.phone || t('demo_success_d_mid')} {t('demo_success_d_post')}</div>
              </div>
            ) : (
              <form onSubmit={submit} className="grid md:grid-cols-2 gap-4">
                <div className="md:col-span-1">
                  <label className="mono text-[10px] tracking-widest text-white/45 mb-2 block">{t('demo_l_name')}</label>
                  <input className="field" placeholder={t('demo_p_name')} value={form.name} onChange={set('name')} required data-hot />
                </div>
                <div>
                  <label className="mono text-[10px] tracking-widest text-white/45 mb-2 block">{t('demo_l_phone')}</label>
                  <div className="flex">
                    <span className="px-3 py-3.5 rounded-l-xl bg-white/[0.04] border border-white/10 border-r-0 text-white/60 mono text-sm">+91</span>
                    <input className="field rounded-l-none" placeholder={t('demo_p_phone')} value={form.phone} onChange={set('phone')} required data-hot />
                  </div>
                </div>
                <div>
                  <label className="mono text-[10px] tracking-widest text-white/45 mb-2 block">{t('demo_l_company')}</label>
                  <input className="field" placeholder={t('demo_p_company')} value={form.company} onChange={set('company')} data-hot />
                </div>
                <div>
                  <label className="mono text-[10px] tracking-widest text-white/45 mb-2 block">{t('demo_l_city')}</label>
                  <input className="field" placeholder={t('demo_p_city')} value={form.city} onChange={set('city')} data-hot />
                </div>
                <div className="md:col-span-2">
                  <label className="mono text-[10px] tracking-widest text-white/45 mb-2 block">{t('demo_l_industry')}</label>
                  <select className="field" value={form.industry} onChange={set('industry')} data-hot>
                    {['Ceramic & Tiles','Real Estate','Healthcare','Manufacturing','Other'].map((o)=> <option key={o}>{o}</option>)}
                  </select>
                </div>
                <div className="md:col-span-2 mt-2">
                  <Magnetic as="button" type="submit" className="btn-primary w-full py-4 rounded-xl font-medium text-base flex items-center justify-center gap-2">
                    <span>📞</span><span>{t('demo_btn')}</span>
                  </Magnetic>
                </div>
              </form>
            )}
            <div className="hairline my-7"></div>
            <div className="flex flex-col sm:flex-row items-center justify-center gap-4 sm:gap-8 text-sm text-white/55">
              <div>{t('demo_or_call')} <span className="text-white/85 mono">{HUNARA.phone}</span></div>
              <div className="hidden sm:block w-px h-4 bg-white/10"></div>
              <div>{t('demo_wa')} <span className="text-white/85 mono">{HUNARA.phone}</span></div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- FAQ ----------
function FaqItem({ q, a, i }) {
  const [open, setOpen] = uS(false);
  return (
    <div className={`glass rounded-2xl ${open ? 'open' : ''}`} style={{
      borderColor: open ? 'rgba(0,240,255,0.35)' : undefined,
      boxShadow: open ? '0 0 32px -10px rgba(0,240,255,0.4)' : 'none',
      transition: 'box-shadow .3s ease, border-color .3s ease',
    }}>
      <button data-hot onClick={()=>setOpen(!open)} className="w-full text-left p-6 flex items-start justify-between gap-6">
        <div className="flex items-start gap-4">
          <span className="mono text-xs text-cyan1/80 mt-1.5">0{i+1}</span>
          <span className="text-base md:text-lg font-display font-medium text-white">{q}</span>
        </div>
        <svg className="chev w-5 h-5 text-white/60 flex-shrink-0 mt-1" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><polyline points="6 9 12 15 18 9"/></svg>
      </button>
      <div className="overflow-hidden transition-all duration-400" style={{ maxHeight: open ? 220 : 0, opacity: open ? 1 : 0 }}>
        <div className="px-6 pb-6 pl-[60px] text-white/65 text-sm leading-relaxed">{a}</div>
      </div>
    </div>
  );
}

function FaqSection() {
  const { t } = useLang();
  const faqs = [
    [t('faq_q1'), t('faq_a1')],
    [t('faq_q2'), t('faq_a2')],
    [t('faq_q3'), t('faq_a3')],
    [t('faq_q4'), t('faq_a4')],
    [t('faq_q5'), t('faq_a5')],
    [t('faq_q6'), t('faq_a6')],
  ];
  return (
    <section id="faq" data-screen-label="08 FAQ" className="relative py-24 md:py-32">
      <div className="mx-auto max-w-4xl px-6 md:px-10">
        <SectionHeader
          tag={t('faq_tag')}
          title={t('faq_title')}
          align="center"
        />
        <div className="space-y-3 reveal">
          {faqs.map(([q, a], i) => <FaqItem key={i} q={q} a={a} i={i} />)}
        </div>
      </div>
    </section>
  );
}

// ---------- FOOTER ----------
function Footer() {
  const { t } = useLang();
  return (
    <footer className="relative pt-20 pb-32 md:pb-12 mt-12 border-t border-white/5">
      <div className="mx-auto max-w-7xl px-6 md:px-10 grid md:grid-cols-12 gap-10">
        <div className="md:col-span-5">
          <div className="flex items-center gap-2.5">
            <span className="relative inline-flex items-center justify-center w-7 h-7 rounded-md" style={{
              background: 'linear-gradient(135deg, #00F0FF, #8B5CF6)',
            }}>
              <span className="text-black font-display font-bold text-[15px]">H</span>
            </span>
            <span className="font-display text-lg font-semibold tracking-tight text-white">Hunara<span className="text-cyan1">AI</span></span>
          </div>
          <p className="text-sm text-white/55 mt-4 max-w-sm">{t('foot_tagline')}</p>
          <div className="mt-5 mono text-[11px] tracking-widest text-white/40">{t('foot_copy')}</div>
        </div>
        <div className="md:col-span-3">
          <div className="mono text-[10px] tracking-widest text-white/40 mb-3">{t('foot_contact')}</div>
          <div className="text-sm text-white/75 mono">{HUNARA.email}</div>
          <div className="text-sm text-white/75 mono mt-1">{HUNARA.phone}</div>
        </div>
        <div className="md:col-span-2">
          <div className="mono text-[10px] tracking-widest text-white/40 mb-3">{t('foot_company')}</div>
          <div className="space-y-2 text-sm">
            <a href="#" className="block text-white/70 hover:text-white" data-hot>{t('foot_privacy')}</a>
            <a href="#" className="block text-white/70 hover:text-white" data-hot>{t('foot_terms')}</a>
          </div>
        </div>
        <div className="md:col-span-2">
          <div className="mono text-[10px] tracking-widest text-white/40 mb-3">{t('foot_explore')}</div>
          <div className="space-y-2 text-sm">
            <a href="#team" className="block text-white/70 hover:text-white" data-hot>{t('foot_team')}</a>
            <a href="#industries" className="block text-white/70 hover:text-white" data-hot>{t('foot_industries')}</a>
            <a href="#demo" className="block text-white/70 hover:text-white" data-hot>{t('foot_book')}</a>
            <a href="https://app.hunaraai.io/login" className="block text-white/70 hover:text-white" data-hot>{t('foot_login')}</a>
          </div>
        </div>
      </div>
      {/* Mobile sticky CTA */}
      <div className="md:hidden fixed bottom-0 left-0 right-0 z-40 grid grid-cols-2 gap-2 p-3 backdrop-blur-xl" style={{ background: 'rgba(6,6,11,0.85)', borderTop: '1px solid rgba(255,255,255,0.06)' }}>
        <a href={`tel:${HUNARA.phone.replace(/\s/g,'')}`} className="btn-primary py-3 rounded-lg text-sm font-medium text-center">📞 {t('foot_call')}</a>
        <a href="#demo" className="btn-whatsapp py-3 rounded-lg text-sm font-medium text-center">💬 {t('foot_wa')}</a>
      </div>
    </footer>
  );
}

Object.assign(window, { Navbar, HowItWorks, IndustriesSection, WhySection, DemoSection, FaqSection, Footer });
