/* ============================================================
   FLORÍADE — Ornamentos (React)
   Roda alquímica, selos, divisores, raios solares, glifos
   ============================================================ */

/* hooks do React disponíveis globalmente para os demais arquivos babel */
Object.assign(window, {
  useState:React.useState, useEffect:React.useEffect, useCallback:React.useCallback,
  useRef:React.useRef, useContext:React.useContext, useMemo:React.useMemo,
  createContext:React.createContext, useReducer:React.useReducer
});

const ZODIAC = ["♈","♉","♊","♋","♌","♍","♎","♏","♐","♑","♒","♓"].map(g=>g+"\uFE0E");
const PLANETS = ["☉","☽","☿","♀","♂","♃","♄"].map(g=>g+"\uFE0E");
const ELEMENTS = ["🜂","🜁","🜄","🜃"]; // fogo, ar, água, terra

function polar(cx, cy, r, deg){
  const a = (deg - 90) * Math.PI/180;
  return [cx + r*Math.cos(a), cy + r*Math.sin(a)];
}

/* Anel de glifos distribuídos (colorFn opcional para colorir por glifo) */
function GlyphRing({ glyphs, r, size, cx=200, cy=200, color="var(--gold)", colorFn, opacity=1 }){
  return glyphs.map((g,i)=>{
    const [x,y] = polar(cx,cy,r, i*360/glyphs.length);
    const c = colorFn ? colorFn(g,i) : color;
    return (
      <text key={i} x={x} y={y} fontSize={size}
        textAnchor="middle" dominantBaseline="central"
        fill={c} opacity={opacity}
        style={{ fontFamily:"'IBM Plex Mono', serif" }}>{g}</text>
    );
  });
}
/* Sol = ouro, Luna = prata, demais = ouro */
const solLunaColor = (g)=> g.indexOf("☽")>=0 ? "var(--silver)" : "var(--gold)";

/* Raios concêntricos (sol radiante, estilo gravura) */
function rays(cx, cy, rIn, rOut, count, w){
  const arr=[];
  for(let i=0;i<count;i++){
    const [x1,y1]=polar(cx,cy,rIn, i*360/count);
    const [x2,y2]=polar(cx,cy,rOut, i*360/count);
    arr.push(<line key={i} x1={x1} y1={y1} x2={x2} y2={y2}
      stroke="var(--gold)" strokeWidth={w} opacity={i%2?0.22:0.5}/>);
  }
  return arr;
}

/* ---------- EMBLEMA SOL·LUNA (coniunctio) ---------- */
/* Disco solar de ouro e crescente de prata lado a lado — as núpcias químicas. */
function SolLuna({ size=72, breathe=false, className="", style={} }){
  const uid = (React.useId ? React.useId() : "sl").replace(/[:]/g,"");
  const mid = "slmoon-"+uid;
  const sx=-12, sy=0; // centro do Sol
  return (
    <svg viewBox="-50 -50 100 100" width={size} height={size}
         className={"solluna"+(breathe?" solluna--breathe":"")+(className?" "+className:"")}
         style={style} aria-hidden="true">
      <defs>
        <mask id={mid}>
          <rect x="-50" y="-50" width="100" height="100" fill="black"/>
          <circle cx="20" cy="0" r="29" fill="white"/>
          <circle cx="4" cy="0" r="26" fill="black"/>
        </mask>
      </defs>
      {/* crescente lunar (prata), concavidade voltada ao Sol */}
      <circle cx="20" cy="0" r="29" fill="var(--silver)" opacity="0.95" mask={`url(#${mid})`}/>
      {/* raios solares (ouro) */}
      <g stroke="var(--gold)" strokeWidth="1.5">
        {Array.from({length:12}).map((_,i)=>{
          const [x1,y1]=polar(sx,sy,19,i*30);
          const [x2,y2]=polar(sx,sy,26,i*30);
          return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} opacity={i%2?0.4:0.95}/>;
        })}
      </g>
      {/* disco solar (ouro) */}
      <circle cx={sx} cy={sy} r="15" fill="none" stroke="var(--gold)" strokeWidth="1.6"/>
      <circle cx={sx} cy={sy} r="2.6" fill="var(--gold)"/>
    </svg>
  );
}

/* ---------- RODA ALQUÍMICA (centro do herói) ---------- */
function AlchemicalWheel({ size=520, spin=true, rays:showRays=true }){
  const sc = spin ? "" : " ";
  return (
    <svg viewBox="0 0 400 400" width={size} height={size} className="alch-wheel"
         style={{ overflow:"visible" }} aria-hidden="true">
      <defs>
        <radialGradient id="aw-glow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="var(--gold)" stopOpacity="0.10"/>
          <stop offset="70%" stopColor="var(--gold)" stopOpacity="0"/>
        </radialGradient>
      </defs>
      <circle cx="200" cy="200" r="196" fill="url(#aw-glow)"/>

      {showRays && (
        <g className={spin?"spin-slow":""} style={{transformBox:"fill-box",transformOrigin:"center"}}>
          {rays(200,200,196,232,72,1)}
        </g>
      )}

      {/* anéis — alternando ouro (Sol) e prata (Luna) */}
      {[{r:188,c:"var(--gold)"},{r:150,c:"var(--silver)"},{r:118,c:"var(--gold)"},{r:86,c:"var(--silver)"},{r:54,c:"var(--gold)"}].map((o,i)=>(
        <circle key={i} cx="200" cy="200" r={o.r} fill="none"
          stroke={o.c} strokeWidth={i===0||i===2?1.1:0.6}
          opacity={i===1?0.5:0.82}/>
      ))}

      {/* zodíaco — anel externo (céu noturno, prata) girando */}
      <g className={spin?"spin-slow":""} style={{transformBox:"fill-box",transformOrigin:"center"}}>
        <GlyphRing glyphs={ZODIAC} r={169} size={15} color="var(--silver)" opacity={0.9}/>
      </g>
      {/* tracinhos entre signos */}
      <g opacity="0.45">
        {ZODIAC.map((_,i)=>{
          const [x1,y1]=polar(200,200,134,i*30+15);
          const [x2,y2]=polar(200,200,150,i*30+15);
          return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke="var(--silver)" strokeWidth="0.6"/>;
        })}
      </g>

      {/* planetas — anel médio girando ao contrário; Sol ouro, Luna prata */}
      <g className={spin?"spin-rev":""} style={{transformBox:"fill-box",transformOrigin:"center"}}>
        <GlyphRing glyphs={PLANETS} r={102} size={15} colorFn={solLunaColor} opacity={0.95}/>
      </g>

      {/* selo central — HEXAGRAMA do coniunctio: fogo △ Sol (ouro) + água ▽ Luna (prata) */}
      <g transform="translate(200 200)">
        <polygon points="0,-46 40,23 -40,23" fill="none" stroke="var(--gold)" strokeWidth="1.2"/>
        <polygon points="0,46 40,-23 -40,-23" fill="none" stroke="var(--silver)" strokeWidth="1.2"/>
        <circle r="30" fill="none" stroke="var(--silver)" strokeWidth="0.6" opacity="0.7"/>
        <circle r="3" fill="var(--gold)"/>
        {/* quatro elementos — ativos (Sol/ouro) e passivos (Luna/prata) */}
        <g strokeWidth="0.9" fill="none">
          {/* fogo △ — Sol */}
          <g transform="translate(0 -20)" stroke="var(--gold)"><polygon points="0,-5 4.5,3 -4.5,3"/></g>
          {/* ar △ com barra — Sol */}
          <g transform="translate(20 0)" stroke="var(--gold)"><polygon points="0,-5 4.5,3 -4.5,3"/><line x1="-2.6" y1="0" x2="2.6" y2="0"/></g>
          {/* água ▽ — Luna */}
          <g transform="translate(0 20)" stroke="var(--silver)"><polygon points="0,5 4.5,-3 -4.5,-3"/></g>
          {/* terra ▽ com barra — Luna */}
          <g transform="translate(-20 0)" stroke="var(--silver)"><polygon points="0,5 4.5,-3 -4.5,-3"/><line x1="-2.6" y1="0" x2="2.6" y2="0"/></g>
        </g>
      </g>
    </svg>
  );
}

/* ---------- LOGO (sprite inline, tintável por color) ---------- */
function Logo({ size, gold=false, className="", style={} }){
  const s = size ? { width:size, height:size } : {};
  return (
    <svg className={"logo"+(gold?" logo--gold":"")+(className?" "+className:"")}
         viewBox="0 0 4000 4000" style={{ ...s, ...style }} aria-label="Floríade" role="img">
      <use href="#fl-mark"/>
    </svg>
  );
}

/* ---------- SELO DA MARCA (logo em anel duplo: prata + ouro) ---------- */
function Seal({ size=120, ring=true, glyphs=true, className="" }){
  return (
    <div className={"seal "+className} style={{ width:size, height:size }}>
      {ring && (
        <svg viewBox="0 0 120 120" className="seal-ring" aria-hidden="true">
          <circle cx="60" cy="60" r="58" fill="none" stroke="var(--silver)" strokeWidth="0.8"/>
          <circle cx="60" cy="60" r="52" fill="none" stroke="var(--gold)" strokeWidth="0.5" opacity="0.7"/>
          {glyphs && (
            <g className="spin-slow" style={{transformBox:"fill-box",transformOrigin:"center"}}>
              <GlyphRing glyphs={["☉","☽","☿","♀","♂","♃","♄","✶"].map(g=>g+"\uFE0E")} r={55} size={6.5} cx={60} cy={60} colorFn={solLunaColor} opacity={0.78}/>
            </g>
          )}
        </svg>
      )}
      <Logo gold className="seal-mark"/>
    </div>
  );
}

/* ---------- DIVISOR ORNAMENTAL ---------- */
function Divider({ glyph="✥", wide=false }){
  return (
    <div className={"divider"+(wide?" divider--wide":"")} role="separator">
      <span className="divider-line"></span>
      <span className="divider-node">
        <span className="divider-diamond"></span>
        <span className="divider-glyph">{glyph}</span>
      </span>
      <span className="divider-line"></span>
    </div>
  );
}

/* ---------- Glifo decorativo inline ---------- */
function Glyph({ g, className="" }){
  return <span className={"glyph "+className} aria-hidden="true">{g}</span>;
}

/* ---------- Microinteração: glifo voa até o carrinho ---------- */
function flyToCart(srcEl, glyph="☉"){
  try{
    const cart = document.querySelector(".cart-btn");
    if(!cart || !srcEl) return;
    if(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const a = srcEl.getBoundingClientRect(), b = cart.getBoundingClientRect();
    const x0 = a.left+a.width/2, y0 = a.top+a.height/2;
    const dx = (b.left+b.width/2) - x0, dy = (b.top+b.height/2) - y0;
    const fly = document.createElement("span");
    fly.textContent = glyph;
    fly.className = "fly-glyph";
    fly.style.left = x0+"px"; fly.style.top = y0+"px";
    fly.style.color = glyph.indexOf("☽")>=0 ? "var(--silver)" : "var(--gold)";
    document.body.appendChild(fly);
    const anim = fly.animate([
      { transform:"translate(-50%,-50%) translate(0,0) scale(1) rotate(0deg)", opacity:1 },
      { transform:`translate(-50%,-50%) translate(${dx*0.5}px, ${dy*0.5 - 70}px) scale(1.1) rotate(120deg)`, opacity:1, offset:0.5 },
      { transform:`translate(-50%,-50%) translate(${dx}px, ${dy}px) scale(.25) rotate(300deg)`, opacity:0.1 }
    ], { duration:780, easing:"cubic-bezier(.45,.05,.5,1)" });
    anim.onfinish = ()=> fly.remove();
  }catch(e){}
}

/* Injeta o sprite da logo inline (referências a arquivo externo falham em alguns runtimes) */
function injectSprite(){
  if(document.getElementById('fl-sprite-holder')) return;
  fetch('assets/floriade-sprite.svg').then(r=>r.text()).then(t=>{
    const div=document.createElement('div');
    div.id='fl-sprite-holder';
    div.setAttribute('aria-hidden','true');
    div.style.cssText='position:absolute;width:0;height:0;overflow:hidden';
    div.innerHTML=t;
    document.body.insertBefore(div, document.body.firstChild);
  });
}
injectSprite();

Object.assign(window, {
  AlchemicalWheel, Seal, Divider, Glyph, GlyphRing, Logo, SolLuna, flyToCart,
  ZODIAC, PLANETS, ELEMENTS, polar
});
