/* FreeToolzHub — Home */
function Pillar({ icon, tone, label }) {
  const { Icon } = window.DesignSystem_3a7ab0;
  const [bg, fg] = window.FTH.TONE_MAP[tone];
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:8, padding:'9px 16px',
      background:'var(--bg-card)', border:'1px solid var(--border-color)',
      borderRadius:'var(--radius-full)', boxShadow:'var(--shadow-xs)',
      fontFamily:'var(--font-body)', fontSize:13, fontWeight:600,
      letterSpacing:'0.03em', textTransform:'uppercase', color:'var(--text-body)',
    }}>
      <span style={{ display:'inline-flex', width:22, height:22, alignItems:'center', justifyContent:'center', borderRadius:'var(--radius-full)', background:bg, color:fg }}>
        <Icon name={icon} size={14} strokeWidth={2.4} />
      </span>{label}
    </span>
  );
}

function AdSlot({ label, h=90 }) {
  return (
    <div style={{
      position:'relative', height:h, display:'grid', placeItems:'center', textAlign:'center',
      border:'1px dashed var(--border-strong)', borderRadius:'var(--radius-lg)', color:'var(--text-faint)',
      background:'repeating-linear-gradient(45deg, transparent, transparent 11px, rgba(37,99,235,.04) 11px, rgba(37,99,235,.04) 22px)',
      fontFamily:'var(--font-mono)', fontSize:12,
    }}>
      <span style={{ position:'absolute', top:7, left:11, fontSize:9, letterSpacing:'.14em', textTransform:'uppercase', fontWeight:700, opacity:.7 }}>Advertisement</span>
      {label}
    </div>
  );
}

function Stat({ value, label }) {
  const ref = React.useRef(null);
  const [disp, setDisp] = React.useState(value);
  React.useEffect(() => {
    const m = String(value).match(/^([\d.]+)(.*)$/);
    if (!m || !ref.current || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const target = parseFloat(m[1]), suffix = m[2], dec = (m[1].split('.')[1]||'').length;
    const io = new IntersectionObserver((es) => {
      es.forEach(en => {
        if (!en.isIntersecting) return;
        io.disconnect();
        const t0 = performance.now(), dur = 1100;
        const step = (t) => {
          const p = Math.min(1, (t - t0) / dur), e = 1 - Math.pow(1 - p, 3);
          setDisp((target * e).toFixed(dec) + suffix);
          if (p < 1) requestAnimationFrame(step);
        };
        requestAnimationFrame(step);
      });
    }, { threshold: 0.4 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, [value]);
  return (
    <div style={{ textAlign:'center' }} ref={ref}>
      <div className="fth-stat-val" style={{ fontFamily:'var(--font-heading)', fontWeight:800, fontSize:36, color:'var(--text-strong)', letterSpacing:'-0.02em' }}>{disp}</div>
      <div style={{ fontFamily:'var(--font-body)', fontSize:14, color:'var(--text-muted)', marginTop:4 }}>{label}</div>
    </div>
  );
}

function FaqItem({ q, a }) {
  const { Icon } = window.DesignSystem_3a7ab0;
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ border:'1px solid var(--border-color)', borderRadius:'var(--radius-xl)', background:'var(--bg-card)', overflow:'hidden' }}>
      <button onClick={() => setOpen(v=>!v)} style={{
        width:'100%', textAlign:'left', padding:'18px 20px', display:'flex', justifyContent:'space-between',
        alignItems:'center', gap:14, background:'none', border:'none', cursor:'pointer',
        fontFamily:'var(--font-heading)', fontWeight:600, fontSize:16, color:'var(--text-strong)',
      }}>
        {q}
        <Icon name="chevron-down" size={18} style={{ transform: open?'rotate(180deg)':'none', transition:'transform var(--dur-base)', color:'var(--text-muted)' }} />
      </button>
      {open && <div style={{ padding:'0 20px 20px', fontFamily:'var(--font-body)', fontSize:15, color:'var(--text-muted)', lineHeight:1.6 }}>{a}</div>}
    </div>
  );
}

function Home({ go }) {
  const { ToolCard, Tabs, Badge, Button, Icon } = window.DesignSystem_3a7ab0;
  const { TOOLS, CATS, working, count } = window.FTH;
  const [cat, setCat] = React.useState('all');

  const popular = (cat==='all' ? working.filter(t=>t.pop) : working.filter(t => t.cat===cat));
  const tabs = [{ id:'all', label:'Popular' }, { id:'pdf', label:'PDF' }, { id:'image', label:'Image' }, { id:'text', label:'Text' }, { id:'dev', label:'Dev' }, { id:'calc', label:'Calc' }];

  const pillars = [
    { icon:'shield-check', tone:'green', label:'No Watermark' },
    { icon:'user-x', tone:'blue', label:'No Registration' },
    { icon:'zap', tone:'amber', label:'Fast' },
    { icon:'lock', tone:'teal', label:'Secure' },
    { icon:'infinity', tone:'sky', label:'Unlimited' },
  ];
  const steps = [
    ['upload-cloud','Drop your file','Drag & drop or browse. Files stay in your browser — nothing is uploaded.'],
    ['sliders-horizontal','Adjust & preview','Tune settings with a live preview. Watch it process in real time.'],
    ['download','Download free','Grab your clean result instantly. No watermark, no email, no limit.'],
  ];
  const faqs = [
    ['Is everything really free?','Yes — every working tool is 100% free with no hidden limits, trial, or premium upsell.'],
    ['Will my files have a watermark?','Never. Your exports come out clean, exactly as you made them.'],
    ['Do I need an account?','No registration required. Open a tool and start immediately.'],
    ['Are my files private?','PDF and image tools run entirely in your browser — your files never leave your device.'],
    ['Is there any catch?','None. No watermark, no sign-up, no limits — every tool is free and runs right in your browser.'],
  ];

  // Entrance is CSS transform-only (never hides content). Scroll-reveal just
  // adds an `.in` class that triggers a transform slide on inner cards — it
  // never hides anything, so no JS/observer failure can blank the page.
  React.useEffect(() => {
    if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    if (!('IntersectionObserver' in window)) return;
    const els = Array.from(document.querySelectorAll('.fth-reveal'));
    const io = new IntersectionObserver((ents) => {
      ents.forEach(en => { if (en.isIntersecting) { en.target.classList.add('in'); io.unobserve(en.target); } });
    }, { threshold: 0.08, rootMargin: '0px 0px -5% 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);

  // hero typing effect (respects reduced motion)
  const PHRASES = ['100% free, forever.', 'No watermark, ever.', 'Private by design.'];
  const [typed, setTyped] = React.useState(PHRASES[0]);
  React.useEffect(() => {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    let pi = 0, ci = PHRASES[0].length, del = true, alive = true;
    const tick = () => {
      if (!alive) return;
      if (del) { ci--; if (ci <= 0) { del = false; pi = (pi + 1) % PHRASES.length; } }
      else { ci++; if (ci >= PHRASES[pi].length) { del = true; setTyped(PHRASES[pi]); setTimeout(tick, 2600); return; } }
      setTyped(PHRASES[pi].slice(0, Math.max(0, ci)) || '\u00a0');
      setTimeout(tick, del ? 32 : 60);
    };
    const t = setTimeout(tick, 2400);
    return () => { alive = false; clearTimeout(t); };
  }, []);

  return (
    <div>
      {/* HERO */}
      <section className="fth-hero-section" style={{ background:'var(--gradient-hero)', padding:'68px 24px 60px', textAlign:'center', position:'relative', overflow:'hidden' }}>
        <span className="fth-hero-orb" style={{ position:'absolute', top:-80, left:'12%', width:340, height:340, borderRadius:'50%', background:'radial-gradient(circle, var(--blue-300), transparent 68%)', opacity:0.5, filter:'blur(20px)', pointerEvents:'none' }}></span>
        <span className="fth-hero-orb b" style={{ position:'absolute', top:20, right:'8%', width:300, height:300, borderRadius:'50%', background:'radial-gradient(circle, var(--teal-400), transparent 68%)', opacity:0.45, filter:'blur(20px)', pointerEvents:'none' }}></span>
        <span className="fth-shape s1"></span>
        <span className="fth-shape s2"></span>
        <span className="fth-shape s3"></span>
        <span className="fth-shape s4"></span>
        <div className="fth-hero-anim" style={{ maxWidth:780, margin:'0 auto', position:'relative', zIndex:1 }}>
          <div style={{ display:'inline-flex', marginBottom:20 }}>
            <Badge tone="teal" variant="soft" icon="badge-check">100% Free • No Registration • No Watermark</Badge>
          </div>
          <h1 style={{ fontFamily:'var(--font-heading)', fontWeight:800, fontSize:54, lineHeight:1.16, letterSpacing:'-0.025em', color:'var(--text-strong)', margin:0 }}>
            Every tool you need.<br/><span className="fth-shimmer">{typed}</span><span className="fth-caret" aria-hidden="true"></span>
          </h1>
          <p style={{ fontFamily:'var(--font-body)', fontSize:19, lineHeight:1.55, color:'var(--text-muted)', maxWidth:600, margin:'20px auto 30px' }}>
            Convert, compress, and edit files right in your browser. No account, no watermark, no limits — your files never leave your device.
          </p>
          <div style={{ display:'flex', gap:12, justifyContent:'center', flexWrap:'wrap', marginBottom:30 }}>
            <Button variant="primary" size="lg" iconLeft="grid-2x2" onClick={() => go('/tools')}>Explore all tools</Button>
            <Button variant="secondary" size="lg" iconLeft="zap" onClick={() => go('/tool/merge-pdf')}>Try Merge PDF</Button>
          </div>
          <div style={{ display:'flex', gap:8, justifyContent:'center', flexWrap:'wrap', marginBottom:26 }}>
            {[['merge-pdf','Merge PDF'],['compress-pdf','Compress PDF'],['image-compressor','Image Compressor'],['remove-background','Remove Background'],['json-formatter','JSON Formatter']].map(([id,label]) => (
              <button key={id} className="fth-quick-chip" onClick={() => go('/tool/'+id)}>{label}</button>
            ))}
          </div>
          <div style={{ display:'flex', gap:10, justifyContent:'center', flexWrap:'wrap' }}>
            {pillars.map(p => <Pillar key={p.label} {...p} />)}
          </div>
        </div>
      </section>

      <div style={{ maxWidth:1140, margin:'0 auto', padding:'28px 24px 0' }}><AdSlot label="728 × 90 — Leaderboard" /></div>

      {/* POPULAR / WORKING TOOLS */}
      <section style={{ background:'var(--gradient-hero)', borderTop:'1px solid var(--border-color)', borderBottom:'1px solid var(--border-color)' }}>
        <div style={{ maxWidth:1140, margin:'0 auto', padding:'48px 24px' }}>
        <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', marginBottom:24, flexWrap:'wrap', gap:16 }}>
          <div>
            <h2 style={{ fontFamily:'var(--font-heading)', fontWeight:700, fontSize:30, color:'var(--text-strong)', margin:0, letterSpacing:'-0.02em' }}>Ready-to-use tools</h2>
            <p style={{ fontFamily:'var(--font-body)', fontSize:15, color:'var(--text-muted)', margin:'6px 0 0' }}>Fully functional, right now — drop a file and go.</p>
          </div>
          <div style={{ minWidth:300 }}><Tabs value={cat} onChange={setCat} tabs={tabs} /></div>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:18 }} className="fth-tool-grid fth-reveal fth-stagger">
          {popular.map(t => (
            <ToolCard key={t.id} icon={t.icon} tone={t.tone} title={t.title} description={t.desc} badge={t.badge} onClick={() => go('/tool/'+t.id)} />
          ))}
        </div>
        </div>
      </section>

      {/* CATEGORY GRID */}
      <section style={{ background:'var(--bg-card)', borderTop:'1px solid var(--border-color)', borderBottom:'1px solid var(--border-color)' }}>
        <div style={{ maxWidth:1140, margin:'0 auto', padding:'56px 24px' }}>
          <div style={{ textAlign:'center', marginBottom:36 }}>
            <h2 style={{ fontFamily:'var(--font-heading)', fontWeight:700, fontSize:30, color:'var(--text-strong)', margin:0 }}>Browse by category</h2>
            <p style={{ fontFamily:'var(--font-body)', fontSize:15, color:'var(--text-muted)', margin:'8px 0 0' }}>{count} tools across {CATS.length} categories — more shipping every week.</p>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:16 }} className="fth-tool-grid fth-reveal fth-stagger">
            {CATS.map(c => {
              const [bg,fg] = window.FTH.TONE_MAP[c.tone];
              const n = TOOLS.filter(t => t.cat===c.id).length;
              return (
                <div key={c.id} onClick={() => go('/tools/'+c.id)} className="fth-cat-card" style={{
                  display:'flex', alignItems:'center', gap:14, padding:18, cursor:'pointer',
                  background:'var(--bg-page)', border:'1px solid var(--border-color)', borderRadius:'var(--radius-xl)',
                  transition:'transform var(--dur-slow) var(--ease-out), box-shadow var(--dur-slow)',
                }}>
                  <span style={{ width:48, height:48, borderRadius:'var(--radius-lg)', background:bg, color:fg, display:'grid', placeItems:'center', flexShrink:0 }}><Icon name={c.icon} size={24} /></span>
                  <span style={{ minWidth:0 }}>
                    <span style={{ display:'block', fontFamily:'var(--font-heading)', fontWeight:600, fontSize:16, color:'var(--text-strong)' }}>{c.label}</span>
                    <span style={{ display:'block', fontSize:13, color:'var(--text-muted)' }}>{n} tools</span>
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* PDF + IMAGE SHOWCASE (full captions) */}
      {[
        { id:'pdf',   blurb:'Merge, split, convert, compress, protect and sign — every PDF task, completely free and watermark-free.' },
        { id:'image', blurb:'Compress, resize, crop, convert and enhance your images right in the browser — nothing is uploaded.' },
      ].map((sec, si) => {
        const meta = CATS.find(c => c.id===sec.id) || {};
        const [bg,fg] = window.FTH.TONE_MAP[meta.tone] || ['var(--blue-50)','var(--color-primary)'];
        const list = TOOLS.filter(t => t.cat===sec.id).slice(0,8);
        return (
          <section key={sec.id} style={{ background: si%2 ? 'var(--bg-card)' : 'var(--bg-page)', borderTop:'1px solid var(--border-color)' }}>
            <div style={{ maxWidth:1140, margin:'0 auto', padding:'56px 24px' }}>
              <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:26, flexWrap:'wrap', gap:16 }}>
                <div style={{ display:'flex', alignItems:'center', gap:16 }}>
                  <span style={{ width:56, height:56, borderRadius:'var(--radius-xl)', background:bg, color:fg, display:'grid', placeItems:'center', flexShrink:0 }}><Icon name={meta.icon} size={28} /></span>
                  <div>
                    <h2 style={{ fontFamily:'var(--font-heading)', fontWeight:700, fontSize:28, color:'var(--text-strong)', margin:0, letterSpacing:'-0.02em' }}>{meta.label} Tools</h2>
                    <p style={{ fontFamily:'var(--font-body)', fontSize:15, color:'var(--text-muted)', margin:'6px 0 0', maxWidth:560, lineHeight:1.55 }}>{sec.blurb}</p>
                  </div>
                </div>
                <Button variant="secondary" iconRight="arrow-right" onClick={() => go('/tools/'+sec.id)}>View all {meta.label} tools</Button>
              </div>
              <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:18 }} className="fth-tool-grid fth-reveal fth-stagger">
                {list.map(t => (
                  <ToolCard key={t.id} icon={t.icon} tone={t.tone} title={t.title} description={t.desc} badge={t.badge} onClick={() => go('/tool/'+t.id)} />
                ))}
              </div>
            </div>
          </section>
        );
      })}

      {/* HOW IT WORKS */}
      <section style={{ maxWidth:1140, margin:'0 auto', padding:'60px 24px' }}>
        <div style={{ textAlign:'center', marginBottom:40 }}>
          <h2 style={{ fontFamily:'var(--font-heading)', fontWeight:700, fontSize:30, color:'var(--text-strong)', margin:0 }}>From file to finished in seconds</h2>
          <p style={{ fontFamily:'var(--font-body)', fontSize:15, color:'var(--text-muted)', margin:'8px 0 0' }}>Everything runs locally. Your files are never uploaded to a server.</p>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:20 }} className="fth-3col fth-reveal fth-stagger">
          {steps.map((s,i) => (
            <div key={i} style={{ position:'relative', padding:'30px 26px', background:'var(--bg-card)', border:'1px solid var(--border-color)', borderRadius:'var(--radius-2xl)', boxShadow:'var(--shadow-sm)' }}>
              <span style={{ position:'absolute', top:22, right:26, fontFamily:'var(--font-heading)', fontWeight:800, fontSize:42, color:'var(--bg-subtle)' }}>{i+1}</span>
              <span style={{ width:54, height:54, borderRadius:'var(--radius-lg)', background:'var(--blue-50)', color:'var(--color-primary)', display:'grid', placeItems:'center', marginBottom:16 }}><Icon name={s[0]} size={26} /></span>
              <h3 style={{ fontFamily:'var(--font-heading)', fontWeight:600, fontSize:20, color:'var(--text-strong)', margin:'0 0 8px' }}>{s[1]}</h3>
              <p style={{ fontFamily:'var(--font-body)', fontSize:14.5, color:'var(--text-muted)', margin:0, lineHeight:1.6 }}>{s[2]}</p>
            </div>
          ))}
        </div>
      </section>

      <div style={{ maxWidth:1140, margin:'0 auto', padding:'8px 24px' }}><AdSlot label="970 × 250 — In-content" h={160} /></div>

      {/* STATS */}
      <section style={{ background:'var(--bg-card)', borderTop:'1px solid var(--border-color)', borderBottom:'1px solid var(--border-color)' }}>
        <div style={{ maxWidth:980, margin:'0 auto', padding:'44px 24px', display:'flex', justifyContent:'space-around', gap:24, flexWrap:'wrap' }} className="fth-reveal">
          <Stat value="2.4M+" label="Files processed" />
          <Stat value={count+'+'} label="Free tools" />
          <Stat value="100%" label="Free, no limits" />
          <Stat value="0" label="Watermarks, ever" />
        </div>
      </section>

      {/* FAQ */}
      <div style={{ maxWidth:1140, margin:'0 auto', padding:'56px 24px 0' }}><AdSlot label="728 × 90 — Footer Leaderboard" /></div>
      <section style={{ maxWidth:840, margin:'0 auto', padding:'60px 24px' }}>
        <div style={{ textAlign:'center', marginBottom:32 }}>
          <h2 style={{ fontFamily:'var(--font-heading)', fontWeight:700, fontSize:30, color:'var(--text-strong)', margin:0 }}>Frequently asked questions</h2>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
          {faqs.map((f,i) => <FaqItem key={i} q={f[0]} a={f[1]} />)}
        </div>
      </section>

      {/* CTA */}
      <section style={{ maxWidth:1140, margin:'0 auto', padding:'0 24px 70px' }}>
        <div style={{ position:'relative', textAlign:'center', padding:'56px 32px', borderRadius:'var(--radius-3xl)', overflow:'hidden', background:'var(--gradient-hero)', border:'1px solid var(--border-color)' }}>
          <h2 style={{ fontFamily:'var(--font-heading)', fontWeight:800, fontSize:38, color:'var(--text-strong)', margin:'0 0 12px', letterSpacing:'-0.02em' }}>Ready to get started?</h2>
          <p style={{ fontFamily:'var(--font-body)', fontSize:17, color:'var(--text-muted)', maxWidth:520, margin:'0 auto 26px' }}>Pick a tool and drop your file. No account, no watermark, no limits.</p>
          <Button variant="primary" size="lg" iconLeft="grid-2x2" onClick={() => go('/tools')}>Explore all tools</Button>
          <div style={{ marginTop:34, paddingTop:28, borderTop:'1px solid var(--border-color)' }}>
            <p style={{ fontFamily:'var(--font-body)', fontSize:14, fontWeight:600, color:'var(--text-muted)', margin:'0 0 14px', letterSpacing:'0.02em' }}>Follow us for new tools & tips</p>
            <div style={{ display:'flex', gap:12, justifyContent:'center', flexWrap:'wrap' }}>
              {[['twitter','Twitter'],['github','GitHub'],['linkedin','LinkedIn'],['youtube','YouTube'],['instagram','Instagram'],['facebook','Facebook']].map(([s,label]) => (
                <a key={s} href="#" aria-label={label} className="fth-social" style={{ width:46, height:46, borderRadius:'var(--radius-lg)', background:'var(--bg-card)', border:'1px solid var(--border-color)', display:'grid', placeItems:'center', color:'var(--text-body)', transition:'transform var(--dur-base) var(--ease-out), background var(--dur-base), color var(--dur-base), box-shadow var(--dur-base)' }}>
                  <Icon name={s} size={20} />
                </a>
              ))}
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}
window.FTHHome = Home;
window.FTHAdSlot = AdSlot;
