/* ============================================================
   FLORÍADE — Loja + Produto
   ============================================================ */

function PageHead({ eyebrow, title, sub }){
  return (
    <div className="pagehead">
      <div className="vine vine--thin"></div>
      <div className="wrap center">
        <div className="eyebrow"><Glyph g="✶"/> {eyebrow}</div>
        <h1 className="display pagehead-title">{title}</h1>
        {sub && <p className="lead pagehead-sub">{sub}</p>}
        <Divider glyph="✥"/>
      </div>
    </div>
  );
}

function Loja({ go, initialLine="todos" }){
  const [line, setLine] = useState(initialLine);
  const [sort, setSort] = useState("curado");
  useEffect(()=>{ setLine(initialLine||"todos"); },[initialLine]);

  let list = PRODUCTS.filter(p=> line==="todos" || p.line===line);
  if(sort==="precoAsc") list = [...list].sort((a,b)=>a.price-b.price);
  if(sort==="precoDesc") list = [...list].sort((a,b)=>b.price-a.price);
  if(sort==="nome") list = [...list].sort((a,b)=>a.name.localeCompare(b.name,"pt-BR"));

  return (
    <div className="view view-loja" data-screen-label="Loja">
      <PageHead eyebrow="Apothecarius · Catálogo Vivo"
        title="A Loja"
        sub="Oito essências, quatro vias, sete planetas. Escolha pela flor, pelo astro ou pela necessidade da alma."/>
      <div className="section loja-body">
        <div className="wrap-wide">
          <div className="loja-bar">
            <div className="filters">
              {LINES.map(l=>(
                <button key={l.id} className={"chip"+(line===l.id?" is-on":"")} onClick={()=>setLine(l.id)}>{l.label}</button>
              ))}
            </div>
            <div className="sort">
              <span className="eyebrow eyebrow--ink">Ordenar</span>
              <select value={sort} onChange={e=>setSort(e.target.value)} aria-label="Ordenar">
                <option value="curado">Curadoria</option>
                <option value="precoAsc">Preço ↑</option>
                <option value="precoDesc">Preço ↓</option>
                <option value="nome">Nome A–Z</option>
              </select>
            </div>
          </div>
          <div className="grid grid-3">
            {list.map((p,i)=> <ProductCard key={p.id} p={p} index={i} onOpen={id=>go("produto",id)}/>)}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- PÁGINA DE PRODUTO ---------- */
function CorrTable({ p }){
  const rows = [
    ["Planeta", <span className="corr-v"><span className="glyph">{p.planet}</span>{p.planetName}</span>],
    ["Signo", <span className="corr-v"><span className="glyph">{p.sign}</span>{signName(p.sign)}</span>],
    ["Elemento", <span className="corr-v"><ElementMark element={p.element} size={14}/>{p.elementName}</span>],
    ["Processo", <span className="corr-v" style={{fontStyle:"italic"}}>{p.process}</span>],
    ["Linha", <span className="corr-v">{p.lineLabel}</span>],
  ];
  return (
    <div className="corr-table">
      {rows.map(([k,v],i)=>(
        <div className="corr-row" key={i}>
          <span className="corr-k eyebrow eyebrow--ink">{k}</span>
          {v}
        </div>
      ))}
    </div>
  );
}
function signName(g){
  const m={"♈":"Áries","♉":"Touro","♊":"Gêmeos","♋":"Câncer","♌":"Leão","♍":"Virgem","♎":"Libra","♏":"Escorpião","♐":"Sagitário","♑":"Capricórnio","♒":"Aquário","♓":"Peixes"};
  return m[g]||"";
}

function Produto({ id, go }){
  const p = PRODUCTS.find(x=>x.id===id) || PRODUCTS[0];
  const cart = useCart();
  const [qty, setQty] = useState(1);
  useEffect(()=>{ setQty(1); window.scrollTo(0,0); },[id]);
  const related = PRODUCTS.filter(x=>x.id!==p.id && (x.line===p.line || x.planet===p.planet)).slice(0,3);
  const relFill = related.length<3 ? [...related, ...PRODUCTS.filter(x=>x.id!==p.id && !related.includes(x))].slice(0,3) : related;

  return (
    <div className="view view-produto" data-screen-label="Produto">
      <div className="vine vine--thin"></div>
      <div className="pdp wrap-wide">
        <button className="crumb" onClick={()=>go("loja")}>← Loja</button>
        <div className="pdp-grid">
          <div className="pdp-media">
            <div className="pdp-img frame frame--gold">
              <image-slot id={"product-"+p.id} shape="rect" fit="cover" placeholder="frasco · foto do produto" style={{width:"100%",height:"100%"}}></image-slot>
              <span className="pdp-sigil"><span className="glyph">{p.planet}</span></span>
            </div>
            <div className="pdp-thumbs">
              <div className="pdp-thumb frame is-on"><image-slot id={"product-"+p.id} shape="rect" placeholder="" style={{width:"100%",height:"100%"}}></image-slot></div>
              <div className="pdp-thumb frame imgholder"><span className="lbl">detalhe</span></div>
              <div className="pdp-thumb frame imgholder"><span className="lbl">rótulo</span></div>
            </div>
          </div>

          <div className="pdp-info">
            <div className="eyebrow"><Glyph g="✶"/> {p.lineLabel} · {p.process}</div>
            <h1 className="display pdp-name">{p.name}</h1>
            <p className="pdp-latin serif">{p.latin}</p>
            <p className="pdp-tag">{p.tag}</p>
            <p className="pdp-desc">{p.desc}</p>

            <div className="pdp-virtues">
              <p className="eyebrow eyebrow--ink">Virtudes</p>
              <ul>
                {p.virtues.map(v=> <li key={v}><span className="glyph">✥</span> {v}</li>)}
              </ul>
            </div>

            <div className="pdp-buy">
              <span className="pdp-price serif">{brl(p.price)}</span>
              <div className="qty qty--lg">
                <button onClick={()=>setQty(q=>Math.max(1,q-1))} aria-label="Menos">−</button>
                <span>{qty}</span>
                <button onClick={()=>setQty(q=>q+1)} aria-label="Mais">+</button>
              </div>
              <button className="btn btn--solid pdp-add" onClick={()=>{cart.add(p.id,qty); cart.setOpen(true);}}>
                <span>Adicionar à Cesta</span>
              </button>
            </div>

            <div className="pdp-ritual">
              <p className="eyebrow eyebrow--ink" style={{whiteSpace:"nowrap"}}><Glyph g="☽"/> Modo de uso ritual</p>
              <p className="serif pdp-ritual-txt">{p.ritual}</p>
            </div>

            <CorrTable p={p}/>
          </div>
        </div>

        <div className="pdp-related">
          <div className="sec-head"><div className="eyebrow"><Glyph g="✶"/> Afinidades</div><h2 className="display sec-title">Essências em Ressonância</h2></div>
          <div className="grid grid-3">
            {relFill.map((r,i)=> <ProductCard key={r.id} p={r} index={i} onOpen={pid=>go("produto",pid)}/>)}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Loja, Produto });
