/* product.jsx — product detail */

const Product = ({productId, setProductId, setRoute, onConsult, onPiecedConsult}) => {
  const product = byId(productId) || byId('aureveris');
  const [metal, setMetal] = React.useState(product.metal);
  const [size, setSize] = React.useState('US 6');
  const [tab, setTab] = React.useState('story');
  const [open, setOpen] = React.useState({stone: true, care: false, ship: false});

  React.useEffect(() => { setMetal(product.metal); }, [productId]);

  const sizes = ['US 4', 'US 5', 'US 6', 'US 7', 'US 8', 'US 9'];
  const metals = ['yellow', 'white', 'rose', 'platinum'];

  return (
    <div className="page-enter">
      {/* breadcrumb */}
      <div className="shell" style={{padding: '24px 48px 0'}}>
        <div style={{fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-60)'}}>
          <a href="#" onClick={(e) => { e.preventDefault(); setRoute('home'); }}>Home</a>
          <span style={{margin: '0 10px'}}>·</span>
          <a href="#" onClick={(e) => { e.preventDefault(); setRoute('home'); }}>Signature</a>
          <span style={{margin: '0 10px'}}>·</span>
          <span style={{color: 'var(--charcoal)'}}>{product.name}</span>
        </div>
      </div>

      <div className="shell" style={{padding: '32px 48px 64px', display: 'grid', gridTemplateColumns: '1.15fr 1fr', gap: 80, alignItems: 'flex-start'}}>
        {/* gallery */}
        <ProductGallery product={product} />

        {/* info */}
        <div style={{position: 'sticky', top: 90}}>
          {product.tag && <span className="tag">{product.tag}</span>}
          <h1 className="display" style={{fontSize: 'clamp(48px, 5.4vw, 72px)', margin: '14px 0 12px', lineHeight: 1.02}}>
            {product.name}
          </h1>
          <p style={{margin: 0, color: 'var(--ink-60)', fontSize: 15, lineHeight: 1.6}}>
            {product.desc || 'A signature Palaces piece, made to order in our atelier.'}
          </p>

          <div style={{margin: '32px 0', paddingTop: 24, borderTop: '1px solid var(--gold-line)', display: 'flex', alignItems: 'baseline', gap: 16}}>
            <div className="price" style={{fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 36, color: 'var(--royal-night)'}}>
              {fmtAED(product.price)}
            </div>
            <div style={{fontSize: 12, color: 'var(--ink-60)', letterSpacing: '0.06em'}}>incl. VAT · prices linked to gold spot</div>
          </div>

          {/* metal swatches */}
          <div style={{marginBottom: 32}}>
            <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14}}>
              <span className="label">Metal</span>
              <span style={{fontSize: 12, color: 'var(--ink-60)', textTransform: 'capitalize'}}>{metalName(metal)}</span>
            </div>
            <div style={{display: 'flex', gap: 12}}>
              {metals.map((m) => (
                <button key={m} onClick={() => setMetal(m)} title={metalName(m)} style={{
                  width: 44, height: 44, padding: 0,
                  background: metalSwatchBg(m),
                  border: metal === m ? '2px solid var(--royal-night)' : '1px solid var(--ink-20)',
                  cursor: 'pointer',
                  borderRadius: '50%',
                }} aria-label={metalName(m)} />
              ))}
            </div>
          </div>

          {/* size */}
          <div style={{marginBottom: 32}}>
            <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14}}>
              <span className="label">Ring size</span>
              <button className="btn-link" style={{fontSize: 10}}>Size guide</button>
            </div>
            <div className="chip-row">
              {sizes.map((s) => (
                <button key={s} className="chip" data-selected={size === s} onClick={() => setSize(s)}>{s}</button>
              ))}
              <button className="chip">Other</button>
            </div>
          </div>

          {/* CTAs */}
          <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
            <button className="btn btn-primary" style={{width: '100%', padding: '18px 28px'}} onClick={() => onPiecedConsult(product.id)}>
              Consult about this piece
            </button>
            <div style={{display: 'flex', gap: 12}}>
              <button className="btn btn-ghost" style={{flex: 1}}>Add to bag</button>
              <a href="https://wa.me/971545839411" target="_blank" rel="noreferrer" className="btn" style={{flex: 1, background: '#25D366', color: '#FFF', borderColor: '#25D366'}}>WhatsApp</a>
            </div>
            <div style={{display: 'flex', gap: 16, marginTop: 8, color: 'var(--ink-60)', fontSize: 12, justifyContent: 'center'}}>
              <span>· Made to order · 4–6 weeks ·</span>
            </div>
          </div>

          {/* expanders */}
          <div style={{marginTop: 40, borderTop: '1px solid var(--gold-line)'}}>
            <Expander title="Stone & specification" open={open.stone} toggle={() => setOpen({...open, stone: !open.stone})}>
              <SpecGrid product={product} />
            </Expander>
            <Expander title="Care & longevity" open={open.care} toggle={() => setOpen({...open, care: !open.care})}>
              <p style={{margin: 0, color: 'var(--ink-60)', fontSize: 14, lineHeight: 1.65}}>
                Cleaned, re-polished and rhodium-plated complimentary for life. Bring the piece to either showroom or post it to us insured. Steam clean every six months; remove for swimming and gym.
              </p>
            </Expander>
            <Expander title="Shipping & returns" open={open.ship} toggle={() => setOpen({...open, ship: !open.ship})}>
              <ul style={{margin: 0, padding: '0 0 0 16px', color: 'var(--ink-60)', fontSize: 14, lineHeight: 1.75}}>
                <li>UAE: 5–7 working days, complimentary.</li>
                <li>Worldwide: 7–16 days, insured, door-to-door.</li>
                <li>7-day exchange on stock pieces · made-to-order pieces are final sale.</li>
              </ul>
            </Expander>
          </div>
        </div>
      </div>

      {/* trust strip */}
      <div className="shell" style={{padding: '0 48px'}}>
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
          padding: '32px 0',
          borderTop: '1px solid var(--gold-line)',
          borderBottom: '1px solid var(--gold-line)',
          gap: 32,
        }}>
          {[
            {t: 'Made to order', s: 'Cast & set in our atelier'},
            {t: 'Certified', s: 'Stones documented & signed off'},
            {t: 'Hallmarked', s: '18k / 750 Bangkok hallmark'},
            {t: 'Lifetime care', s: 'Complimentary at both showrooms'},
          ].map((i) => (
            <div key={i.t} style={{textAlign: 'center'}}>
              <div style={{fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 17, color: 'var(--royal-night)'}}>{i.t}</div>
              <div style={{fontSize: 12, color: 'var(--ink-60)', marginTop: 4}}>{i.s}</div>
            </div>
          ))}
        </div>
      </div>

      {/* story */}
      <StorySection product={product} />

      {/* you may also love */}
      <YouMayLove currentId={product.id} setProductId={setProductId} />
    </div>
  );
};

// ===========================================================
// Gallery (thumbnails)
// ===========================================================
const ProductGallery = ({product}) => {
  const others = PRODUCTS.filter(p => p.cat === product.cat && p.id !== product.id).slice(0, 3);
  const thumbs = [product.img, ...others.map(p => p.img)];
  const [active, setActive] = React.useState(0);

  React.useEffect(() => { setActive(0); }, [product.id]);
  const main = thumbs[active] || product.img;

  return (
    <div style={{display: 'grid', gridTemplateColumns: '80px 1fr', gap: 16, position: 'sticky', top: 90}}>
      <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
        {thumbs.map((t, i) => (
          <button key={i} onClick={() => setActive(i)} style={{
            aspectRatio: '1/1',
            border: active === i ? '1px solid var(--palace-gold)' : '1px solid var(--ink-10)',
            background: 'var(--champagne)',
            padding: 0,
            overflow: 'hidden',
            cursor: 'pointer',
          }}>
            <img src={t} alt="" style={{width: '100%', height: '100%', objectFit: 'cover'}} />
          </button>
        ))}
      </div>
      <div style={{
        aspectRatio: '4/5',
        background: 'var(--champagne)',
        overflow: 'hidden',
        position: 'relative',
      }}>
        <img src={main} alt={product.name} style={{width: '100%', height: '100%', objectFit: 'cover'}} />
        <button style={{
          position: 'absolute', top: 16, right: 16,
          width: 40, height: 40, border: 0, borderRadius: '50%',
          background: 'rgba(255,255,255,0.9)', cursor: 'pointer',
          display: 'grid', placeItems: 'center',
        }} aria-label="Zoom">
          <Icon.Plus size={14} />
        </button>
      </div>
    </div>
  );
};

// ===========================================================
// Expander
// ===========================================================
const Expander = ({title, open, toggle, children}) => (
  <div style={{borderBottom: '1px solid var(--ink-10)'}}>
    <button onClick={toggle} style={{
      width: '100%',
      padding: '20px 0',
      background: 'transparent',
      border: 0,
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      cursor: 'pointer',
      color: 'var(--charcoal)',
      fontFamily: 'inherit',
      fontSize: 14,
      letterSpacing: '0.04em',
      textTransform: 'uppercase',
      fontWeight: 500,
    }}>
      {title}
      <span style={{color: 'var(--palace-gold)'}}>{open ? <Icon.Minus /> : <Icon.Plus />}</span>
    </button>
    {open && <div style={{padding: '0 0 24px'}}>{children}</div>}
  </div>
);

const SpecGrid = ({product}) => {
  const rows = [
    {label: 'Centre stone', value: stoneFor(product)},
    {label: 'Setting', value: 'Pavé halo, claw prongs'},
    {label: 'Metal', value: `18k ${metalName(product.metal)} · 750 hallmark`},
    {label: 'Total carats', value: '2.18 ct (centre 0.85, accents 1.33)'},
    {label: 'Certification', value: 'IGI lab report with each piece'},
    {label: 'Origin', value: 'Designed Dubai · Cast Bangkok · Finished Deira'},
  ];
  return (
    <dl style={{margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 12}}>
      {rows.map((r) => (
        <div key={r.label} style={{display: 'grid', gridTemplateColumns: '140px 1fr', gap: 16, alignItems: 'baseline'}}>
          <dt className="label" style={{fontSize: 10, margin: 0}}>{r.label}</dt>
          <dd style={{margin: 0, fontSize: 14, color: 'var(--charcoal)'}}>{r.value}</dd>
        </div>
      ))}
    </dl>
  );
};

const stoneFor = (product) => {
  const map = {
    aureveris: 'Sapphire cluster · multi-colour',
    velantrix: 'Emerald cut · 2.10 ct centre',
    seraphelis: 'Round brilliant · 1.20 ct centre',
    'eagle-ring': 'Solid 18k yellow gold · pavé halo',
    'eagle-pendant': 'Solid 18k yellow gold · pavé halo',
    'imperial-eagle': 'Solid 18k · ruby, emerald, sapphire pavé',
    celeste: 'Eternity band · brilliant pavé',
    twilight: 'Pink tourmaline & sapphire cluster',
    midnight: 'Blue sapphire pear · diamond halo',
    prismara: 'Multi-tourmaline butterfly · pavé wings',
    magnolia: 'Diamond marquise drops',
    honeycrest: 'Enamel & pavé hoops',
    'celestial-leaf': 'Diamond marquise leaves',
    skyhold: 'Sapphire solitaire · 0.55 ct',
    'radiant-horizon': 'Diamond baguette & pavé',
    rosabella: 'Pink sapphire & diamond cluster',
    sunlure: 'Yellow citrine & diamond',
    'ember-hoops': 'Garnet & peridot hoops',
    trilight: 'Diamond marquise leaf drops',
  };
  return map[product.id] || 'Mixed gemstone & diamond';
};

const metalSwatchBg = (m) => ({
  yellow: 'linear-gradient(135deg, #F4D78C, #C9A24B 60%, #9A7929)',
  white: 'linear-gradient(135deg, #F1F2F4, #C3C6CC 60%, #95989E)',
  rose: 'linear-gradient(135deg, #F0CAB8, #D69A85 60%, #A86F5A)',
  platinum: 'linear-gradient(135deg, #E6E9ED, #B0B6BD 60%, #80878E)',
})[m];

// ===========================================================
// Story
// ===========================================================
const StorySection = ({product}) => (
  <section className="shell section-pad" style={{display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 72, alignItems: 'center'}}>
    <div>
      <span className="eyebrow">The piece</span>
      <h2 className="display" style={{fontSize: 'clamp(38px, 4.4vw, 60px)', margin: '20px 0 24px', lineHeight: 1.05}}>
        Drawn around the <em>stone.</em>
      </h2>
      <p style={{fontSize: 16, color: 'var(--ink-60)', lineHeight: 1.7, maxWidth: 480}}>
        {product.name} began on the bench as a sketch in graphite. The shank tapers from 1.8mm at the back to 2.4mm at the shoulders to throw light into the halo. The pavé is bead-set by hand, one stone every nine minutes — never machine-cast.
      </p>
      <div style={{display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24, marginTop: 40, paddingTop: 32, borderTop: '1px solid var(--gold-line)'}}>
        {[
          {n: '01', t: 'Sketch'},
          {n: '02', t: 'CAD render'},
          {n: '03', t: 'Wax & cast'},
        ].map((s) => (
          <div key={s.n}>
            <div style={{fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 22, color: 'var(--palace-gold)'}}>{s.n}</div>
            <div style={{fontSize: 13, color: 'var(--charcoal)', marginTop: 6, letterSpacing: '0.04em'}}>{s.t}</div>
          </div>
        ))}
      </div>
    </div>
    <div style={{position: 'relative', aspectRatio: '4/5', background: 'var(--champagne)', overflow: 'hidden'}}>
      <img src={product.img} alt={product.name} style={{width: '100%', height: '100%', objectFit: 'contain', padding: 64}} />
      <div style={{position: 'absolute', top: 0, left: 0, right: 0, height: '50%', background: 'linear-gradient(to bottom, rgba(184, 146, 58, 0.06), transparent)', pointerEvents: 'none'}} />
    </div>
  </section>
);

// ===========================================================
// You may also love
// ===========================================================
const YouMayLove = ({currentId, setProductId}) => {
  const others = PRODUCTS.filter(p => p.id !== currentId).slice(0, 4);
  return (
    <section style={{background: 'var(--section-bg)'}}>
      <div className="shell section-pad">
        <SectionHead
          eyebrow="Together with"
          title={<>Worn <em>alongside.</em></>}
          sub="Pieces that travel well with this one — pulled by stone, by metal, by the consultant."
        />
        <div style={{display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 28}}>
          {others.map((p) => (
            <ProductCard key={p.id} product={p} onOpen={(id) => { setProductId(id); window.scrollTo(0, 0); }} />
          ))}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Product });
