/* GMC FONT — Font Detail with Type Tester */

function FontDetail({ id }) {
  const r = useRoute();
  const a = useApp();
  const fonts = useFonts();
  const font = fonts.find(f => f.id === id) || fonts[0];
  if (!font) return (
    <div style={{padding:"120px 0", textAlign:"center", color:"var(--ink-soft)"}}>
      <div style={{fontSize:48, marginBottom:12}}>⏳</div>
      <div className="display" style={{fontSize:24}}>กำลังโหลด…</div>
    </div>
  );

  const [text, setText] = useState(font.languages.includes("thai") ? "สวัสดีชาวโลก The quick brown fox 1234" : "The quick brown fox jumps over the lazy dog");
  const [size, setSize] = useState(30);
  const [weight, setWeight] = useState(font.weights[Math.floor(font.weights.length/2)] || 400);
  const [bg, setBg] = useState("#FFFCF4");
  const [fg, setFg] = useState("#2C1A14");
  const [italic, setItalic] = useState(false);
  const [align, setAlign] = useState("left");
  const [lineHeight, setLineHeight] = useState(1.1);
  const [letterSpacing, setLetterSpacing] = useState(0);

  const [tab, setTab] = useState("license");            // glyphs | specimens
  const [licenseTier, setLicenseTier] = useState("personal");

  const swatches = ["#FFFCF4","#2C1A14","#F38081","#EFD78D","#ADDDE6","#C8CE72","#F79977"];

  const tierPrice = { personal: font.sale||font.price, commercial: (font.price*2) }[licenseTier] || (font.sale||font.price);

  return (
    <div data-screen-label={`Font: ${font.name}`}>
      {/* breadcrumb */}
      <div className="container" style={{padding:"18px 0 0", fontSize:13, color:"var(--ink-soft)"}}>
        <span onClick={() => r.go("home")} style={{cursor:"pointer"}}>หน้าแรก</span> /
        <span onClick={() => r.go("fonts")} style={{cursor:"pointer"}}> ฟอนต์ทั้งหมด</span> /
        <span style={{color:"var(--ink)", fontWeight:500}}> {font.name}</span>
      </div>

      {/* Top: name + meta */}
      <section style={{padding:"32px 0 24px"}}>
        <div className="container">
          <div style={{display:"flex", justifyContent:"space-between", alignItems:"end", flexWrap:"wrap", gap:24}}>
            <div>
              <div style={{display:"flex", gap:8, marginBottom:10}}>
                {font.new && <span className="sticker coral">NEW DROP</span>}
                {font.hot && <span className="sticker lemon">🔥 HOT</span>}
                <span className="sticker">{font.category.toUpperCase()}</span>
              </div>
              <h1 className="display detail-h1" style={{fontSize:"clamp(48px,6.4vw,96px)", margin:0, lineHeight:.98}}>
                {font.name}
              </h1>
              <div className="detail-meta" style={{display:"flex", gap:14, marginTop:14, color:"var(--ink-soft)", fontSize:14, flexWrap:"wrap"}}>
                <span><b style={{color:"var(--ink)"}}>{font.thai_name}</b></span>
                <span>·</span>
                <span>โดย {font.designer}</span>
                <span>·</span>
                <span>{font.weights.length} น้ำหนัก</span>
                <span>·</span>
                <span style={{display:"inline-flex", alignItems:"center", gap:4}}>
                  <Icon name="star" size={14}/> 4.9 (124)
                </span>
              </div>
            </div>
            <div className="detail-actions" style={{display:"flex", gap:10, alignItems:"center"}}>
              <button className="icon-btn"><Icon name="heart"/></button>
              <button className="btn">แชร์</button>
            </div>
          </div>
        </div>
      </section>

      {/* TESTER */}
      <section style={{paddingBottom:48}}>
        <div className="container">
          <div className="tester">
            {/* control bar */}
            <div className="tester-bar">
              <div className="group">
                <label>ขนาด</label>
                <input type="range" className="range" min="14" max="240" value={size} onChange={e => setSize(+e.target.value)} style={{width:100}} />
                <b style={{minWidth:42, fontFamily:"var(--f-mono)"}}>{size}px</b>
              </div>
              <div style={{marginLeft:"auto", display:"flex", flexDirection:"column", gap:6}}>
                <div className="group">
                  <label style={{minWidth:80}}>สีตัวอักษร</label>
                  {swatches.map(c => (
                    <span key={c} className={`color-swatch ${fg===c?"on":""}`} style={{background:c}} onClick={() => setFg(c)} />
                  ))}
                </div>
                <div className="group">
                  <label style={{minWidth:80}}>พื้นหลัง</label>
                  {swatches.slice().reverse().map(c => (
                    <span key={c} className={`color-swatch ${bg===c?"on":""}`} style={{background:c}} onClick={() => setBg(c)} />
                  ))}
                </div>
              </div>
            </div>
            {/* tester input */}
            <textarea
              className="tester-input"
              value={text}
              onChange={e => setText(e.target.value)}
              style={{
                fontFamily: font.family,
                fontWeight: weight,
                fontStyle: "normal",
                fontSize: size,
                lineHeight: 1.1,
                letterSpacing: 0,
                textAlign: "left",
                color: fg,
                background: bg,
              }}
            />
          </div>

          {/* Special styles preview */}
          {Object.keys(font.special_files || {}).length > 0 && (
            <div style={{marginTop:36, marginBottom:0}}>
              <h3 className="display" style={{fontSize:20, margin:"0 0 14px"}}>แบบพิเศษ</h3>
              <div style={{display:"flex", flexDirection:"column", gap:10}}>
                {Object.entries(font.special_files).map(([variantName]) => {
                  const baseName = (font.family || "").replace(/,.*/, "").replace(/['"]/g, "").trim();
                  const specialFamily = `"${baseName} ${variantName}", ${font.family}`;
                  const sample = SAMPLES[font.category] || SAMPLES.sans;
                  const sampleText = font.languages.includes("thai") ? sample.th : sample.en;
                  return (
                    <div key={variantName} className="card" style={{
                      padding:"18px 24px", display:"grid",
                      gridTemplateColumns:"100px 1fr", alignItems:"center", gap:16,
                      background:`var(--${font.color})`
                    }}>
                      <div style={{fontSize:11, fontWeight:600, color:"var(--ink-soft)",
                        textTransform:"uppercase", letterSpacing:.5, lineHeight:1.3}}>
                        {variantName}
                      </div>
                      <div style={{fontFamily: specialFamily, fontSize: font.sample_size || 48, lineHeight:1.1}}>
                        {sampleText}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Tabs */}
          <div className="tabs" style={{margin:"32px 0 18px"}}>
            {[
              {id:"license", label:"สิทธิการใช้งาน"},
              {id:"specimens", label:"เงื่อนไขการใช้งาน"},
              {id:"glyphs", label:"อักขระ"},
            ].map(t => (
              <button key={t.id} className={tab===t.id?"on":""} onClick={() => setTab(t.id)}>{t.label}</button>
            ))}
          </div>

          {tab === "glyphs" && <GlyphsPanel font={font}/>}
          {tab === "specimens" && <SpecimensPanel font={font}/>}
          {tab === "license" && <BuyPanel font={font} licenseTier={licenseTier} setLicenseTier={setLicenseTier} tierPrice={tierPrice}/>}
        </div>
      </section>

      {/* Reviews */}
      <ReviewsSection font={font}/>

      {/* Related */}
      <section className="section">
        <div className="container">
          <div className="sec-head">
            <h2 className="title display">ฟอนต์ใกล้เคียง</h2>
            <button className="btn sm" onClick={() => r.go("fonts")}>ดูทั้งหมด <Icon name="arrow-r" size={12}/></button>
          </div>
          <div className="grid-4">
            {fonts.filter(f => f.id !== font.id && f.category === font.category).slice(0,4).map(f => <FontCard key={f.id} font={f}/>)}
          </div>
        </div>
      </section>
    </div>
  );
}

function WeightsPanel({ font }) {
  const sample = font.languages.includes("thai") ? "ขนมหวาน — Sweet" : "Cream — Yummy";
  const labels = {300:"บาง", 400:"ปกติ", 500:"ปกติหนา", 600:"หนา", 700:"หนามาก", 800:"หนาพิเศษ", 900:"หนาสุด"};
  return (
    <div className="card" style={{padding:0, overflow:"hidden"}}>
      {font.weights.map((w, i) => (
        <div key={w} className="weight-row" style={{
          padding:"22px 28px",
          borderBottom: i === font.weights.length-1 ? 0 : "1px dashed var(--line)",
          display:"grid", gridTemplateColumns:"120px 1fr 100px", gap:20, alignItems:"center"
        }}>
          <div className="weight-meta" style={{fontSize:14, color:"var(--ink-soft)", fontWeight:500}}>
            {labels[w] || "ปกติ"}
          </div>
          <div className="weight-sample" style={{fontFamily:font.family, fontWeight:w, fontSize:42, lineHeight:1, color:"var(--ink)"}}>
            {sample}
          </div>
          <button className="btn sm">เลือก</button>
        </div>
      ))}
    </div>
  );
}

function GlyphsPanel({ font }) {
  const glyphs = (font.languages.includes("thai")
    ? "ก ข ค ฆ ง จ ฉ ช ซ ฌ ญ ฎ ฏ ฐ ฑ ฒ ณ ด ต ถ ท ธ น บ ป ผ ฝ พ ฟ ภ ม ย ร ล ว ศ ษ ส ห ฬ อ ฮ ะ า ิ ี ึ ื ุ ู ่ ้ ๊ ๋ ์ ํ ๅ"
    : "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 ! ? & @ # $ % * +"
  ).split(" ");
  return (
    <div className="card" style={{padding:20}}>
      <div style={{display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(48px,1fr))", gap:5}}>
        {glyphs.map((g,i) => (
          <div key={i} style={{
            border:"1px solid var(--line)", borderRadius:8,
            display:"grid", placeItems:"center",
            aspectRatio:"1", fontFamily:font.family, fontSize:22,
            background:"var(--white)"
          }}>{g}</div>
        ))}
      </div>
      <div style={{display:"flex", justifyContent:"space-between", marginTop:14, fontSize:13, color:"var(--ink-soft)"}}>
        <span>รวม {glyphs.length} อักขระ + symbols 200+</span>
        <span>OpenType: ligatures, alternates, tabular figures</span>
      </div>
    </div>
  );
}

function SpecimensPanel({ font }) {
  return (
    <div className="card" style={{padding:"32px 36px"}}>
      <div className="display" style={{fontSize:28, marginBottom:18, textAlign:"center"}}>
        เงื่อนไขการใช้งานฟอนต์ gmcfontverse
      </div>

      <div className="license-block">
        <h4>📜 เงื่อนไขทั่วไป</h4>
        <ul>
          <li>ฟอนต์ทุกตัวเป็นทรัพย์สินทางปัญญาของเรา และได้รับความคุ้มครองภายใต้กฎหมายลิขสิทธิ์</li>
          <li>ห้ามคัดลอก ดัดแปลง สร้างผลงานใหม่จากต้นแบบ แจกจ่าย ขายต่อ หรือใช้โดยไม่ได้รับอนุญาตเป็นลายลักษณ์อักษรจากเรา</li>
        </ul>
      </div>

      <div className="license-block">
        <h4>🤖 ข้อกำหนดการใช้งานกับระบบปัญญาประดิษฐ์ (AI)</h4>
        <ul>
          <li>ห้ามนำฟอนต์ หรือส่วนประกอบใดๆ ของฟอนต์ (รวมถึงรูปแบบตัวอักษร ตัว glyph ไฟล์ฟอนต์ หรือกราฟิก/ข้อความที่สร้างขึ้นด้วยฟอนต์ดังกล่าว) ไปใช้กับระบบปัญญาประดิษฐ์ (AI) ทุกประเภทโดยเด็ดขาด</li>
          <li>ข้อห้ามนี้รวมถึงและครอบคลุมการอัปโหลด ป้อนข้อมูล ใช้เพื่อฝึก (Training) สร้าง (Generation) ปรับแต่ง (Editing) วิเคราะห์ (Analysis) หรือประมวลผลด้วย AI ไม่ว่าทางตรงหรือทางอ้อม</li>
          <li>รวมถึงการพิมพ์ข้อความตัวอย่างหรือข้อมูลที่ส่งต่อไปเป็นข้อมูลตั้งต้น (Input) สำหรับระบบ AI ในทุกกรณี</li>
          <li>ห้ามนำไฟล์ฟอนต์ ตัวอักษร หรือภาพใดๆ ที่มีหรือต้องการนำเข้าสู่ระบบ AI ไม่ว่าทางตรงหรือทางอ้อม</li>
          <li>ข้อกำหนดนี้มีผลใช้ทั่วถึงเครื่องมือดิจิทัลทุกประเภทที่เกี่ยวข้องหรือไม่เกี่ยวข้องในขณะนี้</li>
        </ul>
      </div>

      <div className="license-block">
        <h4>⚠️ บทกำหนดค่าปรับและการละเมิด</h4>
        <ul>
          <li>ในกรณีที่ตรวจพบการละเมิดข้อใดข้อหนึ่งหรือทุกข้อของระเบียบนี้ ผู้ละเมิดต้องชำระค่าปรับไม่ต่ำกว่า <b>10,000 บาท</b> ต่อฟอนต์ 1 ตัว หรือต่อ 1 ชิ้นงาน</li>
          <li>หากความเสียหายที่เกิดขึ้นมีมูลค่าสูงกว่าค่าปรับขั้นต่ำ ผู้ครอบครองสิทธิ์มีสิทธิ์เรียกค่าเสียหายเพิ่มเติมตามความเสียหายจริง</li>
          <li>การละเมิดดังกล่าว ทางเราจะดำเนินคดีตามกฎหมายอย่างถึงที่สุด รวมถึงการแจ้งความและฟ้องร้องทางแพ่ง</li>
          <li>ผู้ละเมิดต้องรับผิดชอบในการนำลายเซ็นและผลงานทั้งหมดที่ละเมิดออกจากการเผยแพร่ทุกช่องทาง</li>
          <li>การงดเว้นของสิทธิ์ใดๆ ของเราต่อการละเมิดในกรณีหนึ่ง ไม่ถือเป็นการยกเว้นสิทธิ์ในกรณีอื่นๆ</li>
        </ul>
      </div>

      <div className="license-foot">
        <div>ประกาศโดย <b>บริษัท จีเอ็มซี จำกัด</b> (ผู้ถือลิขสิทธิ์ฟอนต์)</div>
        <div style={{marginTop:4}}>วันที่มีผลบังคับใช้: 1 มกราคม 2026 — ปรับปรุงล่าสุด: 4 พฤษภาคม 2026</div>
      </div>
    </div>
  );
}

function ComparePanel({ font }) {
  const fonts = useFonts();
  const others = fonts.filter(f => f.id !== font.id).slice(0,5);
  const sample = font.languages.includes("thai") ? "ขนมหวาน Yummy" : "The Yummy Quick";
  return (
    <div className="compare-row">
      <div className="crow" style={{background:"var(--lemon)"}}>
        <div className="nm">{font.name} <span className="sticker" style={{fontSize:10, padding:"2px 8px", boxShadow:"none"}}>THIS</span></div>
        <div className="sm" style={{fontFamily:font.family}}>{sample}</div>
        <span></span>
      </div>
      {others.map(o => (
        <div key={o.id} className="crow">
          <div className="nm">{o.name}</div>
          <div className="sm" style={{fontFamily:o.family}}>{sample}</div>
          <button className="icon-btn" style={{width:32, height:32, boxShadow:"none"}}><Icon name="close" size={14}/></button>
        </div>
      ))}
      <button className="btn ghost" style={{alignSelf:"start"}}>
        <Icon name="plus" size={14}/> เพิ่มฟอนต์เปรียบเทียบ
      </button>
    </div>
  );
}

function BuyPanel({ font, licenseTier, setLicenseTier, tierPrice }) {
  const a = useApp();
  const r = useRoute();
  const tiers = [
    { id:"personal",   name:"Personal",   th:"ใช้ส่วนตัว",  desc:"สำหรับงานส่วนตัวที่ไม่ใช่เชิงพาณิชย์", mult:1 },
    { id:"commercial", name:"Commercial", th:"เชิงพาณิชย์", desc:"ใช้ในงานลูกค้า โพสต์โซเชียล โฆษณา ใบเสร็จ + ใบอนุญาต PDF", mult:2 },
  ];
  return (
    <div className="card" style={{padding:"16px 20px", background:"var(--white)"}}>
      <h3 className="display" style={{fontSize:22, margin:"0 0 10px"}}>เลือกสิทธิการใช้งาน</h3>
      <div style={{display:"flex", flexDirection:"column", gap:6}}>
        {tiers.map(t => {
          const on = licenseTier === t.id;
          return (
            <label key={t.id} className="tier-row" style={{
              border:"1px solid var(--line)", borderRadius:10, padding:"8px 12px",
              background: on ? "var(--butter)" : "var(--white)",
              boxShadow: on ? "var(--pillow-sm)" : "none",
              display:"grid", gridTemplateColumns:"20px 1fr auto", gap:10, alignItems:"center", cursor:"pointer"
            }}>
              <input type="radio" name="tier" checked={on} onChange={() => setLicenseTier(t.id)} />
              <div>
                <div style={{fontWeight:500, fontSize:14}}>{t.th} <span style={{color:"var(--ink-soft)", fontWeight:400}}>· {t.name}</span></div>
                <div className="desc" style={{fontSize:12, color:"var(--ink-soft)"}}>{t.desc}</div>
              </div>
              <div style={{textAlign:"right", fontFamily:"var(--f-display-2)", fontSize:18, whiteSpace:"nowrap"}}>
                ฿{(font.sale||font.price) * t.mult}
              </div>
            </label>
          );
        })}
      </div>
      <div style={{display:"flex", gap:8, marginTop:12, alignItems:"center"}}>
        <button className="btn coral" onClick={() => { a.addToCart(font, licenseTier, tierPrice); r.go("cart"); }}>
          <Icon name="cart" size={14}/> เพิ่มลงตะกร้า ฿{tierPrice}
        </button>
        <button className="btn" onClick={() => a.addToCart(font, licenseTier, tierPrice)}>+ ตะกร้า</button>
      </div>
    </div>
  );
}

function DownloadPanel({ font }) {
  return (
    <div className="card" style={{padding:24, background:"var(--sky)"}}>
      <span className="sticker">📥 ดาวน์โหลด</span>
      <h3 className="display" style={{fontSize:28, margin:"12px 0 8px"}}>ดาวน์โหลดทันที</h3>
      <p style={{color:"var(--ink-soft)", marginTop:0}}>หลังชำระเงิน คุณจะได้รับ:</p>
      <div style={{display:"flex", flexDirection:"column", gap:10}}>
        {[
          {f:"gmcfontverse-Khanom.otf", s:"1.2 MB"},
          {f:"gmcfontverse-Khanom.ttf", s:"1.5 MB"},
          {f:"gmcfontverse-Khanom.woff2", s:"480 KB"},
          {f:"gmcfontverse-Khanom-Webfonts.zip", s:"3.4 MB"},
          {f:"gmcfontverse-Khanom-License.pdf", s:"180 KB"},
        ].map(d => (
          <div key={d.f} style={{display:"flex", alignItems:"center", gap:12, padding:"10px 14px", background:"var(--white)", border:"1px solid var(--line)", borderRadius:12}}>
            <Icon name="download" size={16}/>
            <span style={{fontWeight:500, fontSize:14, flex:1, fontFamily:"var(--f-mono)"}}>{d.f}</span>
            <span style={{fontSize:12, color:"var(--ink-soft)"}}>{d.s}</span>
          </div>
        ))}
      </div>
      <button className="btn block lemon" style={{marginTop:14}} onClick={() => alert("ทดลองโหลดเฉพาะตัวอย่าง — กรุณาซื้อใบอนุญาตก่อน")}>
        <Icon name="download" size={16}/> ดาวน์โหลดตัวอย่างฟรี
      </button>
    </div>
  );
}

function ReviewsSection({ font }) {
  const reviews = [
    {n:"ก้อย", role:"Graphic Designer", color:"pink", body:"ใช้ทำ packaging ขนมเลย เด็กมาก เห็นปุ๊บคนจำได้เลย"},
    {n:"Nice", role:"Brand Manager", color:"butter", body:"ฟอนต์ไทยน่ารักหายาก เจอตัวนี้คือจบเลยค่ะ ราคาน่ารักด้วย"},
    {n:"พลอย", role:"Illustrator", color:"sky", body:"คู่กับ Coconut Sans ได้ดีมาก ใช้ทำหนังสือเด็กกำลังลงตัว"},
  ];
  return (
    <section style={{borderTop:"1px solid var(--line)", padding:"14px 0"}}>
      <div className="container">
        <div style={{display:"flex", alignItems:"center", gap:8, marginBottom:8}}>
          <span style={{fontWeight:500, fontSize:12, color:"var(--ink-soft)"}}>รีวิวจากผู้ใช้</span>
          <span style={{color:"var(--coral)", fontSize:11}}>★★★★★</span>
          <span style={{fontWeight:600, fontSize:12}}>4.9</span>
          <span style={{color:"var(--ink-soft)", fontSize:11}}>(124)</span>
        </div>
        <div className="reviews-grid">
          {reviews.map((rv,i) => (
            <div key={i} className="card" style={{padding:"10px 12px", background:`var(--${rv.color})`, opacity:0.85}}>
              <div style={{color:"var(--ink-soft)", fontSize:11}}>★★★★★</div>
              <p style={{fontSize:12, margin:"3px 0 6px", color:"var(--ink)", fontFamily:"var(--f-display)"}}>"{rv.body}"</p>
              <div style={{display:"flex", alignItems:"center", gap:6}}>
                <div style={{width:22, height:22, borderRadius:999, background:"var(--ink-soft)", color:"var(--white)", display:"grid", placeItems:"center", fontWeight:500, fontSize:10}}>{rv.n[0]}</div>
                <div>
                  <div style={{fontWeight:500, fontSize:11, color:"var(--ink)"}}>{rv.n}</div>
                  <div style={{fontSize:10, color:"var(--ink-soft)"}}>{rv.role}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { FontDetail });
