// Product detail page

const ProductPage = () => {
  const { route, setRoute, addToCart, toggleWish, wish } = useApp();
  const p = PRODUCTS.find(x => x.id === route.params?.id) || PRODUCTS[0];
  const hasColors = Array.isArray(p.colors) && p.colors.length > 0;
  const hasSizes = Array.isArray(p.sizes) && p.sizes.length > 0;
  const [color, setColor] = React.useState(hasColors ? p.colors[0] : '');
  const [size, setSize] = React.useState('');
  const [qty, setQty] = React.useState(1);
  const [img, setImg] = React.useState(0);
  const [openAcc, setOpenAcc] = React.useState('details');
  const liked = wish.includes(p.id);
  React.useEffect(() => {
    setColor((p.colors && p.colors[0]) || '');
    setSize(''); setQty(1); setImg(0);
  }, [p.id]);
  const related = PRODUCTS.filter(x => x.cat === p.cat && x.id !== p.id).slice(0, 4);

  const handleAdd = () => {
    if (hasSizes && !size) return;
    addToCart({ id: p.id, name: p.name, price: p.price, color, size, qty });
  };

  return (
    <>
      <Breadcrumb items={[
        { label: 'Home', onClick: () => setRoute('home') },
        { label: 'Shop', onClick: () => setRoute('shop') },
        { label: CATEGORIES.find(c => c.slug === p.cat)?.name || '', onClick: () => setRoute('shop', { cat: p.cat }) },
        { label: p.name },
      ]}/>
      <section style={{ paddingBottom: 80 }}>
        <div className="container-wide" style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 64 }} className="pd-grid">
          <div>
            {p.img
              ? <img src={p.img} alt={p.name}
                  style={{ width: '100%', aspectRatio: '4/5', objectFit: 'cover', display: 'block', marginBottom: 8 }}/>
              : <div className="ph" data-label={`${p.id} · ${String(img+1).padStart(2,'0')}`} style={{ aspectRatio: '4/5', marginBottom: 8 }}/>}
            {!p.img && (
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
                {[0,1,2,3].map(i => (
                  <button key={i} onClick={() => setImg(i)} style={{ padding: 0, border: 0 }}>
                    <div className="ph" data-label={`0${i+1}`} style={{ aspectRatio: '1/1', outline: img === i ? '1px solid var(--ink)' : 'none', outlineOffset: 2 }}/>
                  </button>
                ))}
              </div>
            )}
          </div>

          <div style={{ position: 'sticky', top: 100, alignSelf: 'start' }}>
            <div className="eyebrow">{p.series} · {p.sku}</div>
            <h1 className="display" style={{ fontSize: 36, margin: '10px 0 4px' }}>{p.name}</h1>
            {p.zh && <div style={{ fontSize: 14, color: 'var(--mute)' }}>{p.zh}</div>}
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 16, fontFamily: 'var(--f-mono)' }}>
              {p.old && <span style={{ color: 'var(--mute)', textDecoration: 'line-through', fontSize: 14 }}>{fmtPrice(p.old)}</span>}
              <span style={{ fontSize: 22, color: p.old ? 'var(--accent)' : 'var(--ink)' }}>{fmtPrice(p.price)}</span>
              {p.old && <span className="tag-pill accent" style={{ height: 22, fontSize: 10 }}>SAVE {Math.round((1-p.price/p.old)*100)}%</span>}
            </div>

            <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 12, color: 'var(--accent)' }}>
              {[1,2,3,4,5].map(i => <IconStar key={i} size={12}/>)}
              <span style={{ color: 'var(--mute)', fontSize: 11, marginLeft: 6 }}>4.9 · 128 reviews</span>
            </div>

            {hasColors && (
              <div style={{ marginTop: 28 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                  <div className="eyebrow">Color: {color}</div>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  {p.colors.map(cn => {
                    const c = COLORS.find(x => x.n === cn);
                    return c && (
                      <button key={cn} onClick={() => setColor(cn)}
                        className={cx('swatch', color === cn && 'active')}
                        style={{ background: c.v, width: 28, height: 28 }} title={cn}/>
                    );
                  })}
                </div>
              </div>
            )}

            <div style={{ marginTop: 24 }}>
              {hasSizes && (
                <>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
                    <div className="eyebrow">Size {size && `· ${size}`}</div>
                    <a href="#" style={{ fontSize: 11, textDecoration: 'underline', color: 'var(--mute)' }}>Size Guide</a>
                  </div>
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    {SIZES.map(s => {
                      const avail = p.sizes.includes(s);
                      return (
                        <button key={s} onClick={() => avail && setSize(s)}
                          className={cx('chip', size === s && 'active', !avail && 'disabled')}>{s}</button>
                      );
                    })}
                  </div>
                </>
              )}
              <div style={{ fontSize: 11, color: 'var(--mute)', marginTop: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: p.stock > 5 ? 'var(--ok)' : (p.stock > 0 ? 'var(--accent)' : 'var(--mute)') }}/>
                {p.stock > 5
                  ? `現貨 · 庫存 ${p.stock}`
                  : (p.stock > 0 ? `僅剩 ${p.stock} 件` : '暫時缺貨')}
              </div>
            </div>

            <div style={{ marginTop: 28, display: 'flex', gap: 12, alignItems: 'stretch' }}>
              <div style={{ display: 'inline-flex', border: '1px solid var(--ink)', height: 48 }}>
                <button style={{ width: 40 }} onClick={() => setQty(Math.max(1, qty - 1))}><IconMinus size={14}/></button>
                <div style={{ width: 40, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--f-mono)' }}>{qty}</div>
                <button style={{ width: 40 }} onClick={() => setQty(qty + 1)}><IconPlus size={14}/></button>
              </div>
              <button className="btn" style={{ flex: 1 }} onClick={handleAdd}
                disabled={(hasSizes && !size) || p.stock === 0}>
                {p.stock === 0
                  ? '暫時缺貨'
                  : (hasSizes && !size ? 'Select a size' : 'Add to bag')
                } · {fmtPrice(p.price * qty)}
              </button>
              <button onClick={() => toggleWish(p.id)}
                style={{ width: 48, height: 48, border: '1px solid var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: liked ? 'var(--accent)' : 'var(--ink)' }}>
                <IconHeart size={18} style={{ fill: liked ? 'var(--accent)' : 'none' }}/>
              </button>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 24, fontSize: 11, color: 'var(--mute)' }}>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><IconTruck size={16}/> 滿 NT$2,000 免運</div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><IconReturn size={16}/> 7 天退換</div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><IconShield size={16}/> 正品保證</div>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}><IconPin size={16}/> 門市可取</div>
            </div>

            <div style={{ marginTop: 32, borderTop: '1px solid var(--line)' }}>
              {[['details', '商品細節', p.details.map((d,i) => <li key={i} style={{ padding: '4px 0' }}>{d}</li>)],
                ['desc', '商品描述', <p style={{ lineHeight: 1.7, color: 'var(--mute)' }}>{p.desc}</p>],
                ['shipping', '配送與退換', <div style={{ color: 'var(--mute)', lineHeight: 1.7 }}>宅配 2-3 個工作天。消費滿 NT$2,000 免運,未達者 NT$120。商品七日內未拆封可退換。</div>],
              ].map(([key, title, body]) => (
                <div key={key} style={{ borderBottom: '1px solid var(--line)' }}>
                  <button onClick={() => setOpenAcc(openAcc === key ? '' : key)}
                    style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', padding: '16px 0', fontSize: 13, fontWeight: 500 }}>
                    {title} <IconChevronDown size={16} style={{ transform: openAcc === key ? 'rotate(180deg)' : 'none', transition: 'transform 0.2s' }}/>
                  </button>
                  {openAcc === key && <div style={{ padding: '4px 0 20px', fontSize: 13 }}><ul style={{ listStyle: 'none', padding: 0 }}>{body}</ul></div>}
                </div>
              ))}
            </div>
          </div>
        </div>
        <style>{`@media (max-width: 900px) { .pd-grid { grid-template-columns: 1fr !important; gap: 32px !important; } }`}</style>
      </section>

      <section style={{ padding: '60px 0', borderTop: '1px solid var(--line)' }}>
        <div className="container-wide">
          <div className="sec-head">
            <div className="t"><div className="eyebrow">You may also like</div><h2>More from {CATEGORIES.find(c => c.slug === p.cat)?.name}</h2></div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }} className="rel-grid">
            {related.map(r => <ProductCard key={r.id} p={r}/>)}
          </div>
          <style>{`@media (max-width: 900px) { .rel-grid { grid-template-columns: repeat(2, 1fr) !important; } }`}</style>
        </div>
      </section>
    </>
  );
};

Object.assign(window, { ProductPage });
