/* ===========================================================
   راویار — Shared components (window globals)
   =========================================================== */

/* ---- Icon set ---- */
function Icon({ name, size = 18, stroke = 1.6, style }) {
  const p = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none',
    stroke: 'currentColor', strokeWidth: stroke, strokeLinecap: 'round', strokeLinejoin: 'round', style };
  const paths = {
    sword: <><path d="M14.5 4.5 20 4l-.5 5.5-9 9-5 .5.5-5.5z"/><path d="M5 19l3-3M14.5 9.5 18 6"/></>,
    heart: <path d="M12 20s-7-4.5-9.3-9C1 7.5 3 4.5 6.2 4.5c1.9 0 3.2 1 3.8 2 .6-1 1.9-2 3.8-2C17 4.5 19 7.5 17.3 11 15 15.5 12 20 12 20z"/>,
    bird: <><path d="M3 7c4 0 6 2 9 2 4 0 6-3 9-3-1 5-4 7-7 7"/><path d="M7 16c2 3 6 4 9 2"/><path d="M14 6 16 4"/></>,
    tower: <><path d="M7 21V7l5-3 5 3v14"/><path d="M10 21v-5h4v5M7 11h10M7 15h10"/></>,
    book: <><path d="M4 5c0-1 1-2 3-2 3 0 5 1.5 5 1.5S14 3 17 3c2 0 3 1 3 2v13c0 1-1 1.5-3 1.5-3 0-5-1.5-5-1.5s-2 1.5-5 1.5c-2 0-3-.5-3-1.5z"/><path d="M12 4.5v15"/></>,
    sun: <><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M5 5l1.5 1.5M17.5 17.5 19 19M19 5l-1.5 1.5M6.5 17.5 5 19"/></>,
    search: <><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></>,
    play: <path d="M8 5.5v13l11-6.5z" fill="currentColor" stroke="none"/>,
    plus: <path d="M12 5v14M5 12h14"/>,
    sparkle: <path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z" fill="currentColor" stroke="none"/>,
    bell: <><path d="M6 9a6 6 0 0 1 12 0c0 5 2 6 2 6H4s2-1 2-6z"/><path d="M10 20a2 2 0 0 0 4 0"/></>,
    filter: <path d="M3 5h18M6 12h12M10 19h4"/>,
    grid: <><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></>,
    layers: <><path d="m12 3 9 5-9 5-9-5z"/><path d="m3 13 9 5 9-5M3 18l9 5 9-5" opacity=".5"/></>,
    users: <><circle cx="9" cy="8" r="3.2"/><path d="M3.5 20c.6-3 3-4.5 5.5-4.5S14 17 14.5 20"/><path d="M16 5.5a3 3 0 0 1 0 5.5M17 15.5c2 .4 3.6 1.8 4 4.5"/></>,
    chart: <><path d="M4 20V4M20 20H4"/><path d="M8 16v-4M12 16V8M16 16v-7"/></>,
    link: <><path d="M9 13a4 4 0 0 0 6 .5l2-2a4 4 0 0 0-5.5-5.5L10.5 7"/><path d="M15 11a4 4 0 0 0-6-.5l-2 2A4 4 0 0 0 12.5 18l1.5-1.5"/></>,
    settings: <><circle cx="12" cy="12" r="3"/><path d="M12 2.5v2M12 19.5v2M21.5 12h-2M4.5 12h-2M18 6l-1.5 1.5M7.5 16.5 6 18M18 18l-1.5-1.5M7.5 7.5 6 6"/></>,
    image: <><rect x="3" y="4" width="18" height="16" rx="2.5"/><circle cx="8.5" cy="9.5" r="1.6"/><path d="m4 17 4.5-4.5L13 16l3-2.5 5 4.5"/></>,
    pen: <><path d="M4 20l4-1 10-10-3-3L5 16z"/><path d="M14 6l3 3"/></>,
    clock: <><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/></>,
    check: <path d="M5 12.5 10 17 19 7"/>,
    queue: <><path d="M4 7h12M4 12h12M4 17h8"/><circle cx="20" cy="17" r="1.6" fill="currentColor" stroke="none"/></>,
    chevron: <path d="m9 6 6 6-6 6"/>,
    globe: <><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.5 2.5 2.5 15 0 18M12 3c-2.5 2.5-2.5 15 0 18"/></>,
    arrowR: <path d="M5 12h14M13 6l6 6-6 6"/>,
    eye: <><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="2.8"/></>,
    flame: <path d="M12 3s5 4 5 9a5 5 0 0 1-10 0c0-2 1-3 1-3s0 2 1.5 2C11 13 9.5 9 12 3z"/>,
    chat: <><path d="M4 5.5h16v11H9l-4 3.5v-3.5H4z"/><path d="M8.5 11h7M8.5 8h7"/></>,
    phone: <path d="M5 4h3l1.5 4-2 1.5a11 11 0 0 0 5 5l1.5-2 4 1.5v3c0 1-1 2-2 2A15 15 0 0 1 4 6c0-1 1-2 1-2z"/>,
    share: <><circle cx="6" cy="12" r="2.5"/><circle cx="17" cy="6" r="2.5"/><circle cx="17" cy="18" r="2.5"/><path d="M8.2 10.8 14.8 7.2M8.2 13.2l6.6 3.6"/></>,
    instagram: <><rect x="3.5" y="3.5" width="17" height="17" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17" cy="7" r="1.1" fill="currentColor" stroke="none"/></>,
    telegram: <path d="M21 4 3 11l5 2 2 6 3-4 5 4z" strokeLinejoin="round"/>,
    youtube: <><rect x="3" y="6" width="18" height="12" rx="3.5"/><path d="M10.5 9.5v5l4-2.5z" fill="currentColor" stroke="none"/></>,
    x: <path d="M5 5l14 14M19 5 5 19" strokeWidth="1.9"/>,
    aparat: <><circle cx="12" cy="12" r="8.5"/><circle cx="12" cy="12" r="3"/><circle cx="12" cy="4.6" r="1.2" fill="currentColor" stroke="none"/><circle cx="12" cy="19.4" r="1.2" fill="currentColor" stroke="none"/><circle cx="4.6" cy="12" r="1.2" fill="currentColor" stroke="none"/><circle cx="19.4" cy="12" r="1.2" fill="currentColor" stroke="none"/></>,
    coin: <><circle cx="12" cy="12" r="8.5"/><path d="M9.5 14l2.5-5 2.5 5M10.3 12.3h3.4"/></>,
    headset: <><path d="M5 13a7 7 0 0 1 14 0"/><rect x="3.5" y="13" width="3.5" height="6" rx="1.5"/><rect x="17" y="13" width="3.5" height="6" rx="1.5"/><path d="M19 19a4 4 0 0 1-4 3h-2"/></>,
    send: <path d="M4 12 20 4l-6 16-3-7z" strokeLinejoin="round"/>,
  };
  return <svg {...p}>{paths[name] || null}</svg>;
}

/* ---- Logo (shamseh + wordmark) ---- */
function Logo({ size = 30 }) {
  return (
    <div className="row gap-2" style={{ alignItems: 'center' }}>
      <span style={{ fontFamily: 'var(--display)', fontSize: size, color: 'var(--gold-400)', lineHeight: 1, letterSpacing: 1 }}>{L('راویار', 'Ravyar')}</span>
      <Shamseh size={size * 0.92} />
    </div>
  );
}

/* ---- Shamseh: 8-pointed Persian star medallion ---- */
function Shamseh({ size = 28, glow = true }) {
  const pts = [];
  const cx = 50, cy = 50;
  for (let i = 0; i < 16; i++) {
    const a = (Math.PI / 8) * i - Math.PI / 2;
    const r = i % 2 === 0 ? 46 : 20;
    pts.push(`${cx + r * Math.cos(a)},${cy + r * Math.sin(a)}`);
  }
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" style={{ filter: glow ? 'drop-shadow(0 0 6px rgba(212,169,76,.5))' : 'none' }}>
      <defs>
        <linearGradient id="shg" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="#e7c673"/><stop offset="1" stopColor="#b88c2e"/>
        </linearGradient>
      </defs>
      <polygon points={pts.join(' ')} fill="url(#shg)"/>
      <circle cx="50" cy="50" r="11" fill="#0a1230"/>
      <circle cx="50" cy="50" r="11" fill="none" stroke="#e7c673" strokeWidth="1.4"/>
      <circle cx="50" cy="50" r="4" fill="#45d6c8"/>
    </svg>
  );
}

/* ---- Procedural "AI poster" art (placeholder imagery w/ Persian identity) ---- */
function PosterArt({ grad = ['#10193f', '#1c4392', '#d4a94c'], seed = 1, ratio, children, dim = 0.0 }) {
  const [a, b, c] = grad;
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, background:
        `radial-gradient(120% 90% at ${30 + (seed * 13) % 40}% 12%, ${c}55, transparent 55%),
         radial-gradient(120% 120% at 80% 110%, ${b}, transparent 60%),
         linear-gradient(155deg, ${a}, ${b} 120%)` }} />
      {/* arabesque medallion */}
      <svg viewBox="0 0 200 200" style={{ position: 'absolute', right: '-10%', top: '-12%', width: '70%', opacity: 0.22, color: c, transform: `rotate(${(seed * 23) % 40 - 20}deg)` }}>
        <g fill="none" stroke="currentColor" strokeWidth="1.2">
          {Array.from({ length: 12 }).map((_, i) => {
            const ang = (i / 12) * Math.PI * 2;
            return <path key={i} d={`M100 100 q ${60 * Math.cos(ang)} ${60 * Math.sin(ang) - 30} ${90 * Math.cos(ang)} ${90 * Math.sin(ang)}`} />;
          })}
          <circle cx="100" cy="100" r="44" /><circle cx="100" cy="100" r="64" /><circle cx="100" cy="100" r="86" />
        </g>
      </svg>
      {/* calligraphic flourish */}
      <svg viewBox="0 0 400 200" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, opacity: 0.3, color: c }}>
        <path d="M-20 150 C 80 90, 160 200, 260 130 S 420 90, 440 140" fill="none" stroke="currentColor" strokeWidth="2" />
        <path d="M-20 175 C 100 140, 200 210, 320 160 S 440 150, 460 165" fill="none" stroke="currentColor" strokeWidth="1.2" opacity=".6" />
      </svg>
      {/* grain + vignette */}
      <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(110% 90% at 50% 0%, transparent 50%, rgba(7,13,34,.75))' }} />
      {dim > 0 && <div style={{ position: 'absolute', inset: 0, background: `rgba(7,13,34,${dim})` }} />}
      {children}
    </div>
  );
}

/* ---- Star rating ---- */
function Stars({ value = 5, size = 13 }) {
  return (
    <span className="row" style={{ gap: 2, color: 'var(--gold-400)' }}>
      <Icon name="sparkle" size={size} />
      <b className="fa-num" style={{ fontSize: size + 1, color: 'var(--gold-200)' }}>{OMID.num(value)}</b>
    </span>
  );
}

/* ---- Story poster card ---- */
function StoryCard({ story, onOpen, w = 230, h = 320 }) {
  const cat = OMID.catOf(story.cat);
  const poet = OMID.poetOf(story.poet);
  const [hover, setHover] = React.useState(false);
  return (
    <button className="gold-frame" onClick={() => onOpen && onOpen(story)}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ position: 'relative', width: w, height: h, borderRadius: 'var(--r-md)', overflow: 'hidden',
        flex: '0 0 auto', textAlign: 'start', boxShadow: hover ? 'var(--shadow-pop)' : 'var(--shadow-card)',
        transform: hover ? 'translateY(-6px)' : 'none', transition: 'transform .25s ease, box-shadow .25s ease' }}>
      <PosterArt grad={story.grad} seed={story.id.length} />
      <div style={{ position: 'absolute', inset: 0, padding: 16, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
        <div className="row between" style={{ alignItems: 'flex-start' }}>
          <span className="badge-ai"><Icon name="sparkle" size={11} /> AI</span>
          {story.premium
            ? <span className="chip" style={{ padding: '4px 10px', fontSize: 11, background: 'rgba(7,13,34,.55)', color: 'var(--gold-200)', borderColor: 'rgba(212,169,76,.45)' }}><CoinGlyph size={12} /> {OMID.num(story.unlockCost)}</span>
            : <span className="chip" style={{ padding: '4px 10px', fontSize: 11, background: 'rgba(7,13,34,.45)' }}>{OMID.TX(cat)}</span>}
        </div>
        <div>
          <div style={{ fontSize: 22, fontWeight: 800, textShadow: '0 2px 14px rgba(0,0,0,.6)' }}>{OMID.TX(story)}</div>
          <div className="row between" style={{ marginTop: 6 }}>
            <span className="muted" style={{ fontSize: 12.5 }}>{OMID.TX(poet)}</span>
            <Stars value={story.rating} />
          </div>
          <div className="row gap-2" style={{ marginTop: 12, opacity: hover ? 1 : 0, transition: 'opacity .2s', maxHeight: hover ? 40 : 0 }}>
            <span className="btn btn-gold" style={{ padding: '7px 14px', fontSize: 13 }}><Icon name="play" size={13} /> {L('تماشا', 'Watch')}</span>
            <span className="chip" style={{ padding: '6px 10px' }}><Icon name="clock" size={12} />{OMID.num(story.mins)}′</span>
          </div>
        </div>
      </div>
    </button>
  );
}

/* ---- Rail (horizontal scroller) ---- */
function Rail({ title, sub, children, action }) {
  return (
    <section style={{ marginBottom: 38 }}>
      <div className="row between" style={{ marginBottom: 16, paddingInline: 4 }}>
        <div>
          <div className="eyebrow">{sub}</div>
          <h2 style={{ fontSize: 25, marginTop: 4 }}>{title}</h2>
        </div>
        {action}
      </div>
      <div className="scroll" style={{ display: 'flex', gap: 18, overflowX: 'auto', paddingBottom: 10, scrollSnapType: 'x proximity' }}>
        {children}
      </div>
    </section>
  );
}

/* ---- Inject arabesque background tile into :root ---- */
(function injectArabesque() {
  const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='120' height='120' viewBox='0 0 120 120'>
    <g fill='none' stroke='%23d4a94c' stroke-width='0.8' opacity='0.5'>
      <path d='M60 0 C 75 25, 95 25, 120 60 C 95 95, 75 95, 60 120 C 45 95, 25 95, 0 60 C 25 25, 45 25, 60 0 Z'/>
      <circle cx='60' cy='60' r='16'/><circle cx='60' cy='60' r='30'/>
      <path d='M60 30 L66 54 L90 60 L66 66 L60 90 L54 66 L30 60 L54 54 Z'/>
    </g></svg>`;
  document.documentElement.style.setProperty('--arabesque', `url("data:image/svg+xml,${svg.replace(/\n/g, '').replace(/#/g, '%23').replace(/%23d4a94c/g,'%23d4a94c')}")`);
})();

/* ---- Coin glyph (سکه) ---- */
function CoinGlyph({ size = 16 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24">
      <defs><linearGradient id="cg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#f3e0a8"/><stop offset="1" stopColor="#b88c2e"/></linearGradient></defs>
      <circle cx="12" cy="12" r="10" fill="url(#cg)" stroke="#8a6a1e" strokeWidth="1"/>
      <circle cx="12" cy="12" r="7" fill="none" stroke="#8a6a1e" strokeWidth="1" opacity=".5"/>
      <path d="M9 14.5l3-7 3 7M10 12.2h4" fill="none" stroke="#5a4410" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

/* ---- Coin pill (balance) ---- */
function CoinPill({ value, onClick, size = 'md' }) {
  const pad = size === 'sm' ? '5px 11px' : '8px 14px';
  return (
    <button onClick={onClick} className="row gap-1" style={{ padding: pad, borderRadius: 999,
      background: 'linear-gradient(135deg, rgba(212,169,76,.18), rgba(184,140,46,.12))',
      border: '1px solid rgba(212,169,76,.45)', color: 'var(--gold-200)', fontWeight: 700 }}>
      <CoinGlyph size={size === 'sm' ? 15 : 18} />
      <span className="fa-num" style={{ fontSize: size === 'sm' ? 13 : 15 }}>{OMID.num(value)}</span>
    </button>
  );
}

/* ---- Stat card ---- */
function StatCard({ label, value, unit, delta, deltaUp = true, icon, tint = 'var(--gold-400)' }) {
  return (
    <div className="panel" style={{ padding: 20, position: 'relative', overflow: 'hidden' }}>
      <div className="row between" style={{ marginBottom: 14 }}>
        <span className="muted" style={{ fontSize: 13.5 }}>{label}</span>
        {icon && <span style={{ color: tint }}><Icon name={icon} size={18} /></span>}
      </div>
      <div className="row" style={{ alignItems: 'baseline', gap: 6 }}>
        <b className="fa-num" style={{ fontSize: 30, letterSpacing: -0.5 }}>{value}</b>
        {unit && <span className="muted" style={{ fontSize: 13 }}>{unit}</span>}
      </div>
      {delta && <div className="row gap-1" style={{ marginTop: 8, fontSize: 12.5, color: deltaUp ? 'var(--turq-400)' : 'var(--ochre-400)' }}>
        <span>{deltaUp ? '▲' : '▼'}</span><span className="fa-num">{delta}</span>
      </div>}
    </div>
  );
}

/* ---- Mini bar chart ---- */
function Bars({ data, tint = 'var(--gold-500)', h = 90 }) {
  const max = Math.max(...data);
  return (
    <div className="row" style={{ alignItems: 'flex-end', gap: 5, height: h }}>
      {data.map((v, i) => (
        <div key={i} style={{ flex: 1, height: `${(v / max) * 100}%`, borderRadius: '4px 4px 0 0',
          background: i === data.length - 1 ? 'linear-gradient(180deg,var(--gold-400),var(--gold-600))' : `linear-gradient(180deg, ${tint}, transparent 160%)`,
          opacity: i === data.length - 1 ? 1 : 0.5 }} />
      ))}
    </div>
  );
}

Object.assign(window, { Icon, Logo, Shamseh, PosterArt, Stars, StoryCard, Rail, CoinGlyph, CoinPill, StatCard, Bars });
