// Per Te (beat feed) + Stats + Profile completeness + Wallet
const Icons = window.SonaraIcons;
const { useState } = React;

function FeedTabs({ value, onChange }) {
  const tabs = [
    { v: "perte", l: "Per te" },
    { v: "beat", l: "Beat" },
    { v: "producer", l: "Producer" },
    { v: "servizi", l: "Servizi" },
  ];
  return (
    <div className="feed-tabs">
      {tabs.map(t => (
        <button key={t.v} className={`feed-tab ${value === t.v ? "active" : ""}`} onClick={() => onChange(t.v)}>
          {t.l}
        </button>
      ))}
    </div>
  );
}

function BeatCard({ beat }) {
  const [playing, setPlaying] = useState(beat.playing || false);
  const [fav, setFav] = useState(beat.fav || false);
  return (
    <a href="Beat.html" className="beat">
      <div className={`beat-cover ${beat.cover} ${!playing ? "paused" : ""}`}>
        <div className="gradient"/>
        <div className="beat-noise"/>
        <div className="beat-bars">
          {Array.from({ length: 22 }).map((_, i) => (
            <span key={i} style={{ animationDelay: `${(i % 7) * 0.13}s` }}/>
          ))}
        </div>
        <div className="beat-tags">
          {beat.exclusive && <span className="beat-tag exclusive">Esclusiva</span>}
          <span className="beat-tag">{beat.bpm} BPM</span>
          <span className="beat-tag">{beat.key}</span>
        </div>
        <button className={`beat-fav ${fav ? "on" : ""}`} onClick={(e) => { e.preventDefault(); e.stopPropagation(); setFav(!fav); }}>
          <Icons.star size={13} filled={fav}/>
        </button>
        <button className="beat-play" onClick={(e) => { e.preventDefault(); e.stopPropagation(); setPlaying(!playing); }}>
          {playing ? (
            <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>
          ) : (
            <Icons.play size={14}/>
          )}
        </button>
      </div>
      <div className="beat-info">
        <div className="top">
          <span className="title">{beat.title}</span>
          <span className="price">€{beat.price}</span>
        </div>
        <div className="producer">
          <span className="av">{beat.prodInit}</span>
          {beat.producer}
          {beat.verified && <span className="verified"><Icons.verified size={11}/></span>}
        </div>
        <div className="meta-row">
          <span>{beat.genre}</span>
          <span className="dot"/>
          <span>{beat.duration}</span>
          <span className="dot"/>
          <span>★ {beat.rating}</span>
        </div>
        <div className="bar"><span style={{ "--played": (beat.played || 0) + "%" }}/></div>
      </div>
    </a>
  );
}

function PerTeFeed() {
  const [tab, setTab] = useState("perte");
  const beats = [
    { title: "Notte Rossa", price: "39", bpm: 142, key: "F min", producer: "Yoshi", prodInit: "Y", verified: true, genre: "Trap", duration: "2:48", rating: "4.9", cover: "b1", played: 35, playing: true, fav: false, exclusive: false },
    { title: "Tigre Blu", price: "29", bpm: 90, key: "C min", producer: "Marco Vitale", prodInit: "MV", verified: true, genre: "R&B", duration: "3:12", rating: "4.8", cover: "b2", played: 0, fav: true, exclusive: false },
    { title: "Skyline 04", price: "590", bpm: 138, key: "D min", producer: "Diego K.", prodInit: "DK", verified: true, genre: "Drill", duration: "2:34", rating: "5.0", cover: "b3", played: 0, exclusive: true },
    { title: "Lume", price: "19", bpm: 120, key: "G maj", producer: "Sara R.", prodInit: "SR", verified: false, genre: "Indie", duration: "3:00", rating: "4.6", cover: "b4", played: 0 },
    { title: "Vetro Caldo", price: "45", bpm: 128, key: "A min", producer: "Vale Frey", prodInit: "VF", verified: true, genre: "Pop", duration: "2:55", rating: "4.7", cover: "b5", played: 0 },
    { title: "Sud", price: "35", bpm: 100, key: "E min", producer: "Tommy O.", prodInit: "TO", verified: false, genre: "Hip-hop", duration: "3:20", rating: "4.5", cover: "b6", played: 0 },
  ];
  return (
    <div>
      <div className="section-head">
        <span className="t">Per te</span>
        <a href="Feed.html" className="more">Tutti i suggerimenti <Icons.chevronRight size={14}/></a>
      </div>
      <FeedTabs value={tab} onChange={setTab}/>
      <div className="beats-grid">
        {beats.map((b, i) => <BeatCard key={i} beat={b}/>)}
      </div>
    </div>
  );
}

function Sparkline({ points = [3, 5, 4, 7, 6, 9, 8], color = "#7b55d0" }) {
  const max = Math.max(...points);
  const w = 100, h = 22;
  const step = w / (points.length - 1);
  const d = points.map((p, i) => `${i === 0 ? "M" : "L"}${i * step},${h - (p / max) * h}`).join(" ");
  return (
    <svg className="spark" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <path d={d} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function StatsCard() {
  return (
    <div className="stats-card">
      <div className="section-head" style={{ marginBottom: 0 }}>
        <span className="t">Le tue stats <span className="count">7gg</span></span>
        <a href="Profilo.html" className="more">Dettagli <Icons.chevronRight size={14}/></a>
      </div>
      <div className="stats-grid">
        <div className="stat">
          <span className="label">Visite profilo</span>
          <span className="num">124</span>
          <span className="delta up">↑ 32% vs settimana scorsa</span>
          <Sparkline points={[2, 3, 5, 4, 7, 8, 11]}/>
        </div>
        <div className="stat">
          <span className="label">Ascolti showcase</span>
          <span className="num">328</span>
          <span className="delta up">↑ 18%</span>
          <Sparkline points={[4, 5, 6, 7, 9, 8, 12]} color="#22c55e"/>
        </div>
        <div className="stat">
          <span className="label">Salvataggi</span>
          <span className="num">14</span>
          <span className="delta flat">stesso del solito</span>
          <Sparkline points={[2, 2, 3, 2, 3, 3, 3]} color="#7b55d0"/>
        </div>
        <div className="stat">
          <span className="label">Rating medio</span>
          <span className="num">4,9 ★</span>
          <span className="delta up">su 7 collab</span>
          <Sparkline points={[5, 5, 4, 5, 5, 5, 5]} color="#f59e0b"/>
        </div>
      </div>
    </div>
  );
}

function ProfileCompleteness() {
  const pct = 65;
  const r = 24, c = 2 * Math.PI * r;
  const items = [
    { t: "Foto profilo", pts: 15, done: true },
    { t: "Generi e città", pts: 10, done: true },
    { t: "Bio breve", pts: 10, done: true },
    { t: "Link Spotify / Instagram", pts: 10, done: false },
    { t: "Carica una traccia showcase", pts: 25, done: false },
    { t: "Verifica email", pts: 5, done: true },
  ];
  return (
    <div className="profile-card">
      <div className="profile-head">
        <div className="profile-ring">
          <svg width="56" height="56" viewBox="0 0 56 56">
            <circle cx="28" cy="28" r={r} stroke="var(--muted)" strokeWidth="5" fill="none"/>
            <circle cx="28" cy="28" r={r} stroke="url(#g1)" strokeWidth="5" fill="none"
              strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - pct/100)}/>
            <defs>
              <linearGradient id="g1" x1="0" y1="0" x2="56" y2="56">
                <stop offset="0%" stopColor="#7b55d0"/>
                <stop offset="100%" stopColor="#41228e"/>
              </linearGradient>
            </defs>
          </svg>
          <span className="pct">{pct}%</span>
        </div>
        <div className="meta">
          <div className="t">Completa il profilo</div>
          <div className="s">Profili sopra l'80% ricevono <strong style={{ color: "var(--violet-bright, #7b55d0)" }}>3× più</strong> visite.</div>
        </div>
      </div>
      <div className="completion-list">
        {items.map((it, i) => (
          <div key={i} className={`completion-item ${it.done ? "done" : ""}`}>
            <span className="check-circle">{it.done && <Icons.check size={12}/>}</span>
            <span>{it.t}</span>
            <span className="pts">+{it.pts}</span>
            {!it.done && <span className="arrow"><Icons.arrowRight size={14}/></span>}
          </div>
        ))}
      </div>
    </div>
  );
}

function WalletCard() {
  return (
    <div className="wallet-card">
      <div className="label">Saldo wallet</div>
      <div className="balance"><span className="ccy">€</span>25,00</div>
      <div className="promo">+ €10,00 promo benvenuto · scade in 14 giorni</div>
      <div className="acts">
        <a href="Wallet.html" className="btn btn-primary">
          <Icons.zap size={14}/> Ricarica
        </a>
        <a href="Wallet.html" className="btn btn-ghost">Storico</a>
      </div>
    </div>
  );
}

Object.assign(window, { PerTeFeed, BeatCard, StatsCard, ProfileCompleteness, WalletCard });
