/* GMC FONT — All Fonts catalog page */

function AllFonts() {
  const r = useRoute();
  const params = new URLSearchParams(r.query || "");
  const initialCat = params.get("cat") || "all";

  const [category, setCategory] = useState(initialCat);
  const [language, setLanguage] = useState("all");
  const [sort, setSort] = useState("featured");
  const [view, setView] = useState("grid");      // grid | list
  const [query, setQuery] = useState("");
  const [priceMax, setPriceMax] = useState(500);
  const [showFree, setShowFree] = useState(false);

  const fonts = useFonts();

  useEffect(() => {
    setCategory(initialCat);
  }, [initialCat]);

  const filtered = useMemo(() => {
    let arr = fonts.filter(f => {
      if (category === "new" && !f.new) return false;
      if (category === "hot" && !f.hot) return false;
      if (category === "featured" && !f.featured) return false;
      if (language === "thai" && !f.languages.includes("thai")) return false;
      if (language === "english" && !f.languages.includes("english")) return false;
      if (language === "bilingual" && !(f.languages.includes("thai") && f.languages.includes("english"))) return false;
      if (query && !(f.name.toLowerCase().includes(query.toLowerCase()) || f.thai_name.includes(query))) return false;
      if ((f.sale || f.price) > priceMax) return false;
      return true;
    });
    if (sort === "new") arr = arr.sort((a,b) => Number(b.new) - Number(a.new));
    else if (sort === "hot") arr = arr.sort((a,b) => Number(b.hot) - Number(a.hot));
    else if (sort === "price-asc") arr = arr.sort((a,b) => (a.sale||a.price) - (b.sale||b.price));
    else if (sort === "price-desc") arr = arr.sort((a,b) => (b.sale||b.price) - (a.sale||a.price));
    return arr;
  }, [fonts, category, language, sort, query, priceMax, showFree]);

  return (
    <div data-screen-label="All Fonts">
      <section style={{padding:"40px 0 24px", borderBottom:"1px solid var(--line)"}}>
        <div className="container">
          <div style={{display:"flex", alignItems:"end", justifyContent:"space-between", flexWrap:"wrap", gap:16}}>
            <div>
              <span className="eyebrow">📚 Library</span>
              <h1 className="display" style={{fontSize:"clamp(36px, 4.5vw, 62px)", margin:"8px 0", lineHeight:1}}>
                ฟอนต์ทั้งหมด
              </h1>
              <p style={{color:"var(--ink-soft)", margin:0}}>เลือกจาก {fonts.length} ฟอนต์ — กรองตามภาษา หมวด ราคา</p>
            </div>
            <div className="field" style={{minWidth:320}}>
              <Icon name="search" size={16}/>
              <input placeholder="ค้นหาฟอนต์..." value={query} onChange={e => setQuery(e.target.value)} />
            </div>
          </div>
          {/* Category pills — scrollable */}
          <div className="cat-scroll" style={{marginTop:24}}>
            <button className={`pill ${category==="all"?"active":""}`} onClick={() => setCategory("all")}>ทั้งหมด</button>
            <button className={`pill ${category==="featured"?"active":""}`} onClick={() => setCategory("featured")}>⭐ แนะนำ</button>
            <button className={`pill ${category==="hot"?"active":""}`} onClick={() => setCategory("hot")}>🔥 ยอดฮิต</button>
            <button className={`pill ${category==="new"?"active":""}`} onClick={() => setCategory("new")}>✦ มือใหม่</button>
          </div>
        </div>
      </section>

      <section className="section-tight">
        <div className="container fonts-grid">
          {/* Filters */}
          <aside className="filters mobile-hide">
            <h3 className="display" style={{fontSize:28, margin:"0 0 8px"}}>ตัวกรอง</h3>
            <div className="filter-group">
              <h4>ภาษา</h4>
              {LANGS.map(l => (
                <label key={l.id} style={{display:"flex", alignItems:"center", gap:8, padding:"4px 0", cursor:"pointer"}}>
                  <input type="radio" name="lang" checked={language===l.id} onChange={() => setLanguage(l.id)} />
                  <span>{l.th}</span>
                </label>
              ))}
            </div>
            <div className="filter-group">
              <h4>ราคา</h4>
              <div style={{display:"flex", justifyContent:"space-between", fontSize:13, color:"var(--ink-soft)"}}>
                <span>฿0</span><span style={{fontWeight:500, color:"var(--ink)"}}>฿{priceMax}</span>
              </div>
              <input type="range" className="range" min="0" max="500" step="10" value={priceMax}
                     onChange={e => setPriceMax(+e.target.value)} style={{width:"100%"}}/>
              <label style={{display:"flex", alignItems:"center", gap:8, marginTop:10, cursor:"pointer"}}>
                <input type="checkbox" checked={showFree} onChange={e => setShowFree(e.target.checked)} />
                <span>ฟอนต์ฟรีเท่านั้น</span>
              </label>
            </div>
            <div className="filter-group">
              <h4>น้ำหนัก</h4>
              <div className="pill-row">
                {["Thin","Light","Regular","Bold","Black"].map(w => (
                  <span key={w} className="pill" style={{fontSize:12, padding:"4px 10px"}}>{w}</span>
                ))}
              </div>
            </div>
            <div className="filter-group">
              <h4>คุณสมบัติ</h4>
              {["ใช้เชิงพาณิชย์ได้","มี italic","มี variable","รองรับภาษาไทย"].map(t => (
                <label key={t} style={{display:"flex", alignItems:"center", gap:8, padding:"4px 0", cursor:"pointer"}}>
                  <input type="checkbox"/>
                  <span style={{fontSize:14}}>{t}</span>
                </label>
              ))}
            </div>
            <button className="btn block sm" style={{marginTop:14}} onClick={() => {
              setLanguage("all"); setSort("featured"); setQuery(""); setPriceMax(500); setShowFree(false);
            }}>ล้างตัวกรอง</button>
          </aside>

          {/* Results */}
          <div>
            <div style={{display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:18, flexWrap:"wrap", gap:10}}>
              <div style={{color:"var(--ink-soft)"}}>
                พบ <b style={{color:"var(--ink)"}}>{filtered.length}</b> ฟอนต์
              </div>
              <div style={{display:"flex", gap:8, alignItems:"center"}}>
                <span style={{fontSize:13, color:"var(--ink-soft)"}}>เรียงตาม:</span>
                <div className="field flat" style={{padding:"6px 12px"}}>
                  <select value={sort} onChange={e => setSort(e.target.value)} style={{border:0, background:"transparent", outline:0, font:"inherit"}}>
                    {SORTS.map(s => <option key={s.id} value={s.id}>{s.th}</option>)}
                  </select>
                </div>
                <div className="tabs">
                  <button className={view==="grid"?"on":""} onClick={() => setView("grid")}><Icon name="grid" size={14}/></button>
                  <button className={view==="list"?"on":""} onClick={() => setView("list")}><Icon name="list" size={14}/></button>
                </div>
              </div>
            </div>
            {filtered.length === 0 ? (
              <div className="card" style={{padding:60, textAlign:"center"}}>
                <div className="display" style={{fontSize:48, marginBottom:8}}>ไม่พบฟอนต์</div>
                <p style={{color:"var(--ink-soft)"}}>ลองเปลี่ยนตัวกรอง หรือคำค้น</p>
              </div>
            ) : view === "grid" ? (
              <div className="grid-3">
                {filtered.map(f => <FontCard key={f.id} font={f}/>)}
              </div>
            ) : (
              <div style={{display:"flex", flexDirection:"column", gap:14}}>
                {filtered.map(f => <FontListRow key={f.id} font={f}/>)}
              </div>
            )}
          </div>
        </div>
      </section>
    </div>
  );
}

function FontListRow({ font }) {
  const r = useRoute();
  const sample = SAMPLES[font.category] || SAMPLES.sans;
  return (
    <div className="card font-row" style={{padding:0, overflow:"hidden", cursor:"pointer"}}
      onClick={() => r.go("detail", font.id)}>
      <div style={{background:`var(--${font.color})`, padding:"20px 22px", display:"grid", placeItems:"center", borderRight:"1px solid var(--line)"}}>
        <div style={{fontFamily:font.family, fontSize:64, lineHeight:1, fontWeight:font.weights[font.weights.length-1]}}>
          {font.languages.includes("thai") ? sample.th : sample.en}
        </div>
      </div>
      <div style={{padding:"18px 22px", display:"flex", flexDirection:"column", justifyContent:"center", gap:8}}>
        <div style={{display:"flex", gap:10, alignItems:"center"}}>
          <h3 style={{margin:0, fontFamily:"var(--f-display)", fontSize:24}}>{font.name}</h3>
          <span style={{color:"var(--ink-soft)"}}>{font.thai_name}</span>
          {font.new && <span className="sticker coral" style={{fontSize:10, padding:"2px 8px", boxShadow:"none"}}>NEW</span>}
          {font.hot && <span className="sticker lemon" style={{fontSize:10, padding:"2px 8px", boxShadow:"none"}}>HOT</span>}
        </div>
        <div style={{color:"var(--ink-soft)", fontSize:14}}>
          {font.designer} · {font.weights.length} weights · {font.languages.join("+")}
        </div>
        <div className="tags">
          {font.tags.map(t => <span key={t} className="tag">{t}</span>)}
        </div>
      </div>
      <div style={{padding:"18px 22px", display:"flex", flexDirection:"column", justifyContent:"center", alignItems:"end", gap:8, borderLeft:"1px solid var(--line)", background:"var(--paper)"}}>
        <div className="display-2" style={{fontSize:24}}>
          {font.sale ? <><s style={{color:"var(--ink-mute)", fontSize:14, marginRight:6}}>฿{font.price}</s>฿{font.sale}</> : <>฿{font.price}</>}
        </div>
        <button className="btn sm coral">ดู <Icon name="arrow-r" size={12}/></button>
      </div>
    </div>
  );
}

Object.assign(window, { AllFonts });
