/* GMC FONT — Shared UI primitives */
const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

/* ============================================================
   ICONS
   ============================================================ */
const Icon = ({ name, size = 18, stroke = 2 }) => {
  const c = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round" };
  const P = {
    search:   <><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></>,
    cart:     <><path d="M5 7h14l-1.5 9.5a2 2 0 0 1-2 1.7H8.5a2 2 0 0 1-2-1.7L5 7Z"/><path d="M9 7V5a3 3 0 0 1 6 0v2"/></>,
    user:     <><circle cx="12" cy="8" r="4"/><path d="M4 21c1.5-4 5-6 8-6s6.5 2 8 6"/></>,
    heart:    <><path d="M12 20s-7-4.35-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 10c0 5.65-7 10-7 10Z"/></>,
    menu:     <><path d="M3 6h18M3 12h18M3 18h18"/></>,
    close:    <><path d="M6 6l12 12M6 18 18 6"/></>,
    "arrow-r":<><path d="M5 12h14M13 6l6 6-6 6"/></>,
    "arrow-l":<><path d="M19 12H5M11 6l-6 6 6 6"/></>,
    download: <><path d="M12 4v12m0 0-4-4m4 4 4-4M4 20h16"/></>,
    check:    <><path d="m5 12 4.5 4.5L20 6"/></>,
    plus:     <><path d="M12 5v14M5 12h14"/></>,
    minus:    <><path d="M5 12h14"/></>,
    filter:   <><path d="M3 5h18M6 12h12M10 19h4"/></>,
    grid:     <><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></>,
    list:     <><path d="M4 6h16M4 12h16M4 18h16"/></>,
    bag:      <><path d="M5 8h14l-1 12H6L5 8Z"/><path d="M9 8a3 3 0 0 1 6 0"/></>,
    ig:       <><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor"/></>,
    fb:       <><path d="M14 8h3V4h-3a4 4 0 0 0-4 4v2H7v4h3v8h4v-8h3l1-4h-4V8Z"/></>,
    yt:       <><rect x="2.5" y="6" width="19" height="12" rx="3"/><path d="m10 9 5 3-5 3V9Z" fill="currentColor"/></>,
    lock:     <><rect x="4.5" y="11" width="15" height="9" rx="2"/><path d="M8 11V8a4 4 0 1 1 8 0v3"/></>,
    mail:     <><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m4 7 8 6 8-6"/></>,
    trash:    <><path d="M4 7h16M9 7V4h6v3m-7 0 1 13h8l1-13"/></>,
    star:     <path d="M12 2.5 14.6 9l6.9.6-5.2 4.5 1.6 6.7L12 17.3 6.1 20.8 7.7 14 2.5 9.6 9.4 9 12 2.5Z" fill="currentColor" stroke="none"/>,
    sparkle:  <><path d="M12 3v6M12 15v6M3 12h6M15 12h6M6 6l3 3M15 15l3 3M18 6l-3 3M9 15l-3 3"/></>,
    fire:     <><path d="M12 3s4 4 4 8a4 4 0 0 1-8 0c0-2 1-3 1-3s0 2 2 2-1-7 1-7Z"/></>,
    bell:     <><path d="M6 16V11a6 6 0 1 1 12 0v5l2 2H4l2-2Z"/><path d="M10 20a2 2 0 0 0 4 0"/></>,
    play:     <path d="M7 5v14l12-7L7 5Z" fill="currentColor" stroke="none"/>,
  };
  return <svg {...c}>{P[name] || null}</svg>;
};

/* ============================================================
   ROUTER (very tiny)
   ============================================================ */
const RouteCtx = createContext(null);
function useRoute() { return useContext(RouteCtx); }

/* ============================================================
   APP CONTEXT (cart, user, etc.)
   ============================================================ */
const AppCtx = createContext(null);
function useApp() { return useContext(AppCtx); }

/* ============================================================
   FONTS CONTEXT
   ============================================================ */
const FontsCtx = createContext([]);
function useFonts() { return useContext(FontsCtx); }

/* ============================================================
   NAV
   ============================================================ */
function Nav() {
  const r = useRoute();
  const a = useApp();
  const links = [
    { id: "home", label: "หน้าแรก", en: "Home" },
    { id: "fonts", label: "ฟอนต์ทั้งหมด", en: "All Fonts" },
  ];
  const isActive = (id) => {
    if (id === r.path) return true;
    if (id.startsWith("fonts?") && r.path.startsWith("fonts")) return r.query === id.split("?")[1];
    return false;
  };
  return (
    <header className="nav">
      <div className="nav-inner">
        <a className="logo" onClick={() => r.go("home")} role="button" data-screen-label="Logo">
          <span className="logo-mark">g</span>
          <span>gmcfontverse</span>
        </a>
        <nav className="nav-links">
          {links.map(l => (
            <a key={l.id} className={isActive(l.id) ? "active" : ""}
               onClick={() => {
                 const [path, query] = l.id.split("?");
                 r.go(path, query || "");
               }}>{l.label}</a>
          ))}
        </nav>

        <div className="nav-right">
          <button className="icon-btn mobile-hide" title="Wishlist"><Icon name="heart"/></button>
          <button className="icon-btn" title="Cart" onClick={() => r.go("cart")}>
            <Icon name="cart"/>
            {a.cart.length > 0 && <span className="badge">{a.cart.length}</span>}
          </button>
          {a.user && isAdminEmail(a.user.email) && (
            <button className="btn sm" style={{background:"var(--butter)"}} onClick={() => r.go("admin")}>⚙️ Admin</button>
          )}
          {a.user ? (
            <button className="btn sm coral" onClick={() => r.go("dashboard")}>
              <Icon name="user" size={16}/> {a.user.name}
            </button>
          ) : (
            <button className="btn sm" onClick={() => r.go("login")}>เข้าสู่ระบบ</button>
          )}
          <button className="icon-btn mobile-only" onClick={() => r.go("fonts")} title="Menu"><Icon name="menu"/></button>
        </div>
      </div>
    </header>
  );
}

/* ============================================================
   FOOTER
   ============================================================ */
function Footer() {
  return (
    <footer className="footer">
      <div className="cols">
        <div>
          <div style={{display:"flex", gap:14, alignItems:"center", marginBottom:14}}>
            <div className="foot-mark">g</div>
            <div className="display" style={{fontSize:28, color:"var(--cream)"}}>gmcfontverse</div>
          </div>
          <p style={{maxWidth:300, opacity:.8, fontSize:14}}>
            สตูดิโอออกแบบฟอนต์ไทย-อังกฤษ ที่เชื่อว่าตัวอักษรน่ารักทำให้โลกอบอุ่นขึ้น 🍯
          </p>
          <div style={{display:"flex", gap:8, marginTop:18}}>
            {["ig","fb","yt"].map(s => (
              <a key={s} style={{width:38,height:38,border:"1.5px solid var(--cream)",borderRadius:10,display:"grid",placeItems:"center"}}>
                <Icon name={s} size={16}/>
              </a>
            ))}
          </div>
        </div>
        <div>
          <h5>ฟอนต์</h5>
          <ul>
            <li><a>ฟอนต์ทั้งหมด</a></li>
            <li><a>ฟอนต์ไทย</a></li>
            <li><a>ฟอนต์อังกฤษ</a></li>
            <li><a>ฟอนต์ฟรี</a></li>
            <li><a>มาใหม่</a></li>
          </ul>
        </div>
        <div>
          <h5>บัญชี</h5>
          <ul>
            <li><a>เข้าสู่ระบบ</a></li>
            <li><a>สมัครสมาชิก</a></li>
            <li><a>คลังฟอนต์</a></li>
            <li><a>ใบเสร็จ</a></li>
          </ul>
        </div>
        <div>
          <h5>ช่วยเหลือ</h5>
          <ul>
            <li><a>ใบอนุญาต</a></li>
            <li><a>ติดตั้งฟอนต์</a></li>
            <li><a>ติดต่อเรา</a></li>
            <li><a>FAQ</a></li>
          </ul>
        </div>
        <div>
          <h5>นักออกแบบ</h5>
          <ul>
            <li><a>เปิดร้านกับเรา</a></li>
            <li><a>ส่งฟอนต์</a></li>
            <li><a>คู่มือนักออกแบบ</a></li>
          </ul>
        </div>
      </div>
      <div className="legal">
        <span>© 2026 gmcfontverse Studio • Made with 🍯 in Bangkok</span>
        <span>เงื่อนไข • ความเป็นส่วนตัว • ใบอนุญาต</span>
      </div>
    </footer>
  );
}

/* ============================================================
   FONT CARD
   ============================================================ */
function FontCard({ font, size = "md" }) {
  const r = useRoute();
  const a = useApp();
  const bg = COLORS[font.color] || COLORS.lemon;
  const circle = { width:34, height:34, minWidth:34, borderRadius:"50%", padding:0, display:"flex", alignItems:"center", justifyContent:"center" };
  return (
    <div className="fcard" onClick={() => r.go("detail", font.id)} data-screen-label={`Font Card: ${font.name}`}>
      <div className="preview" style={{ background: bg, position:"relative" }}>
        {font.image ? (
          <img src={font.image} alt={font.name} loading="lazy" />
        ) : (
          <span style={{ fontFamily: font.family, fontSize: font.sample_size, fontWeight: font.weights[font.weights.length-1] }}>
            {font.languages.includes("thai") ? (SAMPLES[font.category]||SAMPLES.sans).th : (SAMPLES[font.category]||SAMPLES.sans).en}
          </span>
        )}
      </div>
      <div className="info">
        <div style={{display:"flex", alignItems:"center", gap:6}} onClick={e => e.stopPropagation()}>
          <div style={{flex:1}}>
            <h3>{font.name}</h3>
            <div className="price">
              {font.sale ? <><s>฿{font.price}</s> ฿{font.sale}</> : <>฿{font.price}</>}
            </div>
          </div>
          <button className="btn sm coral" style={circle}
            onClick={() => a.addToCart(font)}>
            <Icon name="cart" size={14}/>
          </button>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   SCROLL ROW
   ============================================================ */
function ScrollRow({ children }) {
  return <div className="scroll-x">{children}</div>;
}

/* Newsletter card */
function NewsletterCard() {
  const [done, setDone] = useState(false);
  return (
    <div className="news">
      <div>
        <span className="sticker lemon" style={{marginBottom:14}}>📬 จดหมายข่าว</span>
        <h2>รับฟอนต์ใหม่<br/><span className="hl">ก่อนใคร</span> ทุกอาทิตย์</h2>
        <p style={{maxWidth:420, color:"var(--ink-soft)"}}>
          ส่งดีลพิเศษ ฟอนต์ฟรีรายเดือน และไอเดียการใช้ตัวอักษรให้ถึงอีเมล
        </p>
        <div style={{display:"flex", gap:10, marginTop:18, flexWrap:"wrap"}}>
          <div className="field" style={{minWidth:240}}>
            <Icon name="mail" size={16}/>
            <input placeholder="your@email.com"/>
          </div>
          <button className="btn coral" onClick={() => setDone(true)}>
            {done ? <><Icon name="check" size={14}/> สมัครแล้ว!</> : "สมัครรับ"}
          </button>
        </div>
      </div>
      <div style={{position:"relative", height:240}}>
        {/* decorative typo stack */}
        <div className="float-card" style={{top:0, right:60, background:"var(--lemon)"}}>
          <div className="label">A SAMPLE</div>
          <div className="sample" style={{fontFamily:"'Caprasimo', serif"}}>Hello!</div>
        </div>
        <div className="float-card" style={{top:80, right:0, background:"var(--white)"}}>
          <div className="label">ทดลอง</div>
          <div className="sample" style={{fontFamily:"'Itim', cursive", fontSize:42}}>สวัสดี</div>
        </div>
        <div className="float-card" style={{top:160, right:80, background:"var(--coral)", color:"var(--white)"}}>
          <div className="label" style={{color:"var(--white)"}}>NEW</div>
          <div className="sample" style={{fontFamily:"'Lilita One', cursive", fontSize:42}}>YUM!</div>
        </div>
      </div>
    </div>
  );
}

/* Export */
Object.assign(window, {
  Icon, RouteCtx, useRoute, AppCtx, useApp, FontsCtx, useFonts,
  Nav, Footer, FontCard, ScrollRow, NewsletterCard,
});
