// Main app: nav + hero + 10 modules + sticky TOC + tweaks panel.

const APP_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#5D7052"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = ['#5D7052', '#4A5B41', '#8A6E3D', '#3F6B5E'];

const TOC_ITEMS = [
  { id: 'analyzer', label: '01 · Quick answer' },
  { id: 'reference', label: '02 · Main limits' },
  { id: 'title-limit', label: '03 · Title limits' },
  { id: 'tag-limit', label: '04 · Tag limits' },
  { id: 'description-limit', label: '05 · Description limits' },
  { id: 'personalization-limit', label: '06 · Personalization limits' },
  { id: 'how-to-check', label: '07 · Check your listing', divider: true },
  { id: 'mistakes', label: '08 · Common mistakes' },
  { id: 'faq', label: '09 · FAQ' },
  { id: 'more-limits', label: '10 · More Etsy limits' },
];

function Nav() {
  const [toolsOpen, setToolsOpen] = useState(false);

  useEffect(() => {
    if (!toolsOpen) return;
    const close = () => setToolsOpen(false);
    document.addEventListener('click', close);
    return () => document.removeEventListener('click', close);
  }, [toolsOpen]);

  return (
    <header style={{ position: 'sticky', top: 0, left: 0, right: 0, zIndex: 50, background: 'rgba(253,252,248,0.95)', backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)', borderBottom: '1px solid rgba(222,216,207,0.6)' }}>
      <nav style={{ maxWidth: 1100, margin: '0 auto', padding: '0 24px', height: 56, display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontFamily: "'Nunito',sans-serif" }}>
        {/* Brand */}
        <a href="/" style={{ display: 'flex', alignItems: 'center', gap: 9, textDecoration: 'none' }}>
          <img src="/logo.png" alt="ShopFoundry" style={{ width: 28, height: 28, borderRadius: 6, flexShrink: 0 }} />
          <span style={{ fontFamily: "'Fraunces',serif", fontWeight: 700, fontSize: 17, color: '#2C2C24', fontVariationSettings: "'SOFT' 100,'opsz' 24" }}>ShopFoundry</span>
        </a>

        {/* Center links */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <div style={{ position: 'relative' }}>
            <button
              onClick={(e) => { e.stopPropagation(); setToolsOpen((v) => !v); }}
              style={{ padding: '7px 14px', borderRadius: 999, background: 'transparent', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5, fontFamily: "'Nunito',sans-serif", fontSize: 14.5, fontWeight: 600, color: '#78786C' }}
            >
              Tools
              <svg width="12" height="12" viewBox="0 0 12 12" fill="none" style={{ transition: 'transform 0.2s', transform: toolsOpen ? 'rotate(180deg)' : 'rotate(0deg)' }}>
                <path d="M2 4l4 4 4-4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
            <div
              onClick={(e) => e.stopPropagation()}
              style={{ display: toolsOpen ? 'block' : 'none', position: 'absolute', top: 'calc(100% + 8px)', left: '50%', transform: 'translateX(-50%)', background: 'rgba(253,252,248,0.97)', backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)', border: '1.5px solid rgba(222,216,207,0.8)', borderRadius: 16, boxShadow: '0 12px 36px -8px rgba(93,112,82,0.18)', padding: 6, minWidth: 220, zIndex: 100 }}
            >
              <a href="/listing-workspace.html" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 10, textDecoration: 'none', color: '#2C2C24', fontWeight: 600, fontSize: 14, transition: 'background 0.15s' }} onMouseOver={(e) => (e.currentTarget.style.background = 'rgba(93,112,82,0.08)')} onMouseOut={(e) => (e.currentTarget.style.background = 'transparent')}>
                <span style={{ width: 28, height: 28, borderRadius: 8, background: 'rgba(93,112,82,0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, flexShrink: 0 }}>✍️</span>
                Listing Generator
              </a>
              <a href="/etsy-title-character-limit/index.html" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderRadius: 10, textDecoration: 'none', color: '#2C2C24', fontWeight: 600, fontSize: 14, transition: 'background 0.15s' }} onMouseOver={(e) => (e.currentTarget.style.background = 'rgba(93,112,82,0.08)')} onMouseOut={(e) => (e.currentTarget.style.background = 'transparent')}>
                <span style={{ width: 28, height: 28, borderRadius: 8, background: 'rgba(93,112,82,0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, flexShrink: 0 }}>⚡</span>
                Character Limit Checker
              </a>
            </div>
          </div>
          <a href="/pricing" style={{ padding: '7px 14px', borderRadius: 999, fontFamily: "'Nunito',sans-serif", fontSize: 14.5, fontWeight: 600, color: '#78786C', textDecoration: 'none', transition: 'color 0.2s' }} onMouseOver={(e) => (e.currentTarget.style.color = '#5D7052')} onMouseOut={(e) => (e.currentTarget.style.color = '#78786C')}>Pricing</a>
        </div>

        {/* CTA */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <a href="/auth/signin" style={{ background: 'transparent', color: '#5D7052', borderRadius: 999, fontWeight: 700, padding: '8px 18px', fontSize: 14, fontFamily: "'Nunito',sans-serif", textDecoration: 'none', whiteSpace: 'nowrap', transition: 'background 0.2s' }} onMouseOver={(e) => (e.currentTarget.style.background = 'rgba(93,112,82,0.1)')} onMouseOut={(e) => (e.currentTarget.style.background = 'transparent')}>Sign in</a>
          <a href="/listing-workspace.html" style={{ background: '#5D7052', color: '#F3F4F1', borderRadius: 999, fontWeight: 700, padding: '8px 20px', fontSize: 14, fontFamily: "'Nunito',sans-serif", textDecoration: 'none', whiteSpace: 'nowrap', transition: 'background 0.2s' }} onMouseOver={(e) => (e.currentTarget.style.background = '#4A5B41')} onMouseOut={(e) => (e.currentTarget.style.background = '#5D7052')}>Start free →</a>
        </div>
      </nav>
    </header>
  );
}

// ============================================================
// TOC with scroll-spy via IntersectionObserver
// ============================================================
function TOC() {
  const [active, setActive] = useState('analyzer');

  useEffect(() => {
    const handler = () => {
      // pick the section whose top is closest to (but past) ~140px from top
      const trigger = 160;
      let current = TOC_ITEMS[0].id;
      for (const item of TOC_ITEMS) {
        const el = document.getElementById(item.id);
        if (!el) continue;
        const top = el.getBoundingClientRect().top;
        if (top - trigger <= 0) current = item.id;
      }
      setActive(current);
    };
    handler();
    window.addEventListener('scroll', handler, { passive: true });
    return () => window.removeEventListener('scroll', handler);
  }, []);

  return (
    <aside className="toc">
      <div className="toc-label">On this page</div>
      <ul className="toc-list">
        {TOC_ITEMS.map((item, i) => (
          <React.Fragment key={item.id}>
            {item.divider && <li className="toc-divider" />}
            <li>
              <a
                href={`#${item.id}`}
                className={active === item.id ? 'active' : ''}
                onClick={(e) => {
                  e.preventDefault();
                  const el = document.getElementById(item.id);
                  if (el) {
                    const top = el.getBoundingClientRect().top + window.scrollY - 96;
                    window.scrollTo({ top, behavior: 'smooth' });
                  }
                }}
              >
                {item.label}
              </a>
            </li>
          </React.Fragment>
        ))}
      </ul>
    </aside>
  );
}

// ============================================================
// [1] HERO + LIVE STUDIO
// ============================================================
function Hero() {
  const [mode, setMode] = useState('title');
  const [title, setTitle] = useState(SAMPLE_TITLE);
  const [tags, setTags] = useState(SAMPLE_TAGS);
  const [desc, setDesc] = useState(SAMPLE_DESC);
  const [perso, setPerso] = useState(SAMPLE_PERSO);

  return (
    <section className="hero" id="analyzer">
      <span className="blob moss b-1 b1" />
      <span className="blob clay b-2 b2" />
      <div className="wrap hero-grid">
        {/* TOP: pitch + summary cards */}
        <div className="hero-copy">
          <span className="eyebrow"><span className="dot" /> Etsy title character limit · 2026</span>
          <h1 className="h1" style={{ marginTop: 20 }}>
            Etsy title character limit 2026:<br />
            <span className="accent">140 characters, plus the related Etsy listing limits sellers check most</span>
          </h1>
          <p className="lead hero-sub">
            Check the Etsy title character limit first, then verify the other core listing limits sellers usually need in the same workflow.
          </p>

          <div className="summary-cards">
            <div className="summary-card">
              <span className="label">Title</span>
              <span className="value">140 characters</span>
              <span className="sub">Core Etsy title character limit</span>
            </div>
            <div className="summary-card">
              <span className="label">Tags</span>
              <span className="value">13 tags</span>
              <span className="sub">20 characters each</span>
            </div>
            <div className="summary-card">
              <span className="label">Description</span>
              <span className="value">~10,000 characters</span>
              <span className="sub">Widely cited cap; the opening lines matter most</span>
            </div>
            <div className="summary-card">
              <span className="label">Personalization</span>
              <span className="value">Up to 5 fields</span>
              <span className="sub">Text-box limits can be set from 1 to 1,024 chars</span>
            </div>
          </div>

          <div className="hero-meta">
            <span className="check"><Icon.check /> Official rules called out explicitly</span>
            <span className="check"><Icon.check /> Guidance and recommendations kept separate</span>
            <span className="check"><Icon.check /> Live checker below for draft review</span>
          </div>
        </div>

        {/* BOTTOM: live analyzer */}
        <div className="analyzer">
          <div className="analyzer-head">
            <div className="title">
              <span className="live-dot" />
              Title Studio
            </div>
            <div className="tabs">
              <button className={`tab ${mode==='title'?'active':''}`} onClick={()=>setMode('title')}>Title</button>
              <button className={`tab ${mode==='tags'?'active':''}`} onClick={()=>setMode('tags')}>Tags</button>
              <button className={`tab ${mode==='desc'?'active':''}`} onClick={()=>setMode('desc')}>Description</button>
              <button className={`tab ${mode==='perso'?'active':''}`} onClick={()=>setMode('perso')}>Personalization</button>
            </div>
          </div>
          <div className="analyzer-body">
            {mode === 'title' && (
              <TitleAnalyzer
                text={title}
                setText={setTitle}
                tags={tags}
                setTags={setTags}
                desc={desc}
                setDesc={setDesc}
              />
            )}
            {mode === 'tags'  && <TagsAnalyzer tags={tags} setTags={setTags} title={title} />}
            {mode === 'desc'  && <DescAnalyzer text={desc} setText={setDesc} />}
            {mode === 'perso' && <PersonalizationAnalyzer text={perso} setText={setPerso} />}
          </div>
        </div>
      </div>
    </section>
  );
}

function App() {
  const [t, setTweak] = useTweaks(APP_TWEAK_DEFAULTS);

  useEffect(() => {
    document.documentElement.style.setProperty('--primary', t.accent);
  }, [t.accent]);

  return (
    <>
      <Nav />
      <Hero />

      <div className="page-body">
        <div className="wrap">
          <main className="page-main">
            <MainLimitsTable />
            <TitleSection />
            <TagSection />
            <DescSection />
            <PersonalizationSection />
            <HowToCheck />
            <CommonMistakes />
            <FAQ />
            <MoreLimits />
          </main>
          <TOC />
        </div>
      </div>

      <FinalCTA />
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Accent color">
          <TweakColor
            label="Accent"
            value={t.accent}
            options={ACCENT_OPTIONS}
            onChange={(v)=>setTweak('accent', v)}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

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