// SONARA — Manager Dashboard sections
const MgrIcons = window.SonaraIcons;

const PlayIc = ({ size = 12 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><path d="M5 3l14 9-14 9V3z"/></svg>;
const ChevIc = ({ size = 14 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>;
const StarIc = ({ size = 12, filled = true }) => <svg width={size} height={size} viewBox="0 0 24 24" fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.5"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>;
const ArrIc = ({ size = 14 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>;
const UpIc = ({ size = 12 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 15 12 9 18 15"/></svg>;

/* ─────────── ROSTER overview ─────────── */
const ROSTER = [
  {
    id: "luca", handle: "@lucabianchi", name: "Luca Bianchi", init: "LB",
    genres: "Cantautorato · indie",
    city: "Milano",
    relation: "Esclusiva", since: "8 mesi",
    activity: { kind: "offers", text: "5 offerte sulla richiesta Mix EP 'Restami'", time: "2h fa", urgent: true, accent: "violet" },
    action: "Vedi offerte",
  },
  {
    id: "martina", handle: "@martinarey", name: "Martina Rey", init: "MR",
    genres: "Alt-pop · R&B",
    city: "Bologna",
    relation: "Non-esclusiva", since: "3 settimane",
    activity: { kind: "done", text: "Master completato con Studio Riva · 5★", time: "1g fa", accent: "success" },
    action: "Apri profilo",
  },
  {
    id: "giada", handle: "@giadaverdi", name: "Giada Verdi", init: "GV",
    genres: "Trap · drill",
    city: "Roma",
    relation: "Esclusiva", since: "1 anno · 4 mesi",
    activity: { kind: "open", text: "Cerca beat trap dark · 8 offerte ricevute", time: "3g fa", accent: "violet" },
    action: "Apri profilo",
  },
  {
    id: "edo", handle: "@edopalma", name: "Edoardo Palma", init: "EP",
    genres: "Indie · folk",
    city: "Torino",
    relation: "Esclusiva", since: "2 anni",
    activity: { kind: "stale", text: "Nessuna attività negli ultimi 30 giorni", time: "—", accent: "neutral", warn: true },
    action: "Scrivigli",
  },
  {
    id: "kaya", handle: "@kayalow", name: "Kaya Low", init: "KL",
    genres: "R&B · neo-soul",
    city: "Milano",
    relation: "Project-based", since: "6 settimane",
    activity: { kind: "new", text: "Caricata nuova showcase track 'Mira'", time: "ieri", accent: "violet" },
    action: "Ascolta",
  },
];

function RosterCard() {
  const urgent = ROSTER.filter(a => a.activity.urgent).length;
  return (
    <section>
      <div className="section-head">
        <div className="t">
          Il tuo roster
          <span className="count">{ROSTER.length} attivi</span>
          {urgent > 0 && (
            <span className="ip-urgent-flag info">
              <span className="dot"/> {urgent} richiede attenzione
            </span>
          )}
        </div>
        <a className="more" href="Roster.html">Vedi tutto <ChevIc size={12}/></a>
      </div>

      <div className="roster-list">
        {ROSTER.map(a => (
          <a key={a.id} href={`Artista.html#id=${a.id}`} className={`roster-row ${a.activity.urgent ? "urgent" : ""} ${a.activity.warn ? "stale" : ""}`}>
            <span className="rost-av">{a.init}</span>
            <div className="rost-body">
              <div className="rost-row1">
                <span className="rost-name">{a.name}</span>
                <span className="rost-handle">{a.handle}</span>
                <span className="rost-sep">·</span>
                <span className={`rost-rel ${a.relation === "Esclusiva" ? "excl" : a.relation === "Project-based" ? "proj" : "nonexcl"}`}>
                  {a.relation}
                </span>
              </div>
              <div className="rost-row2">
                <span className="rost-genres">{a.genres}</span>
                <span className="rost-sep">·</span>
                <span className="rost-city">{a.city}</span>
                <span className="rost-sep">·</span>
                <span className="rost-since">Da {a.since}</span>
              </div>
              <div className={`rost-activity ${a.activity.accent}`}>
                <span className="rost-dot"/>
                <span className="rost-act-text">{a.activity.text}</span>
                <span className="rost-act-time">{a.activity.time}</span>
              </div>
            </div>
            <div className="rost-actions">
              <button className={`ip-btn ${a.activity.urgent ? "urgent" : "primary"}`}>{a.action} <ArrIc size={11}/></button>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}

/* ─────────── PENDING INVITES ─────────── */
function PendingInvites() {
  const items = [
    { id: "i1", to: "@simonecaruso", name: "Simone Caruso", init: "SC", sent: "3gg fa", expires: "tra 27gg", relation: "Esclusiva", genres: "Alt-pop · Torino" },
    { id: "i2", to: "@noahmiles", name: "Noah Miles", init: "NM", sent: "1 sett fa", expires: "tra 23gg", relation: "Non-esclusiva", genres: "Indie · Milano" },
  ];
  return (
    <section>
      <div className="section-head sub">
        <div className="t">
          Inviti al roster in attesa
          <span className="count">{items.length}</span>
        </div>
        <a className="more" href="Roster.html#inviti">Tutti <ChevIc size={12}/></a>
      </div>
      <div className="oreq-list">
        {items.map(it => (
          <a key={it.id} href="Roster.html#inviti" className="oreq-row">
            <div className="oreq-icon"><MgrIcons.users size={14}/></div>
            <div className="oreq-body">
              <div className="t">
                <span style={{ fontWeight: 600 }}>{it.name}</span>
                <span className="rost-sep" style={{ margin: "0 6px" }}>·</span>
                <span style={{ color: "var(--muted-foreground)", fontWeight: 400 }}>{it.to}</span>
              </div>
              <div className="s">
                <span>{it.genres}</span>
                <span className="sep">·</span>
                <span>Inviato {it.sent}</span>
                <span className="sep">·</span>
                <strong>Scade {it.expires}</strong>
                <span className="sep">·</span>
                <span className="rost-rel-mini">{it.relation}</span>
              </div>
            </div>
            <div className="rost-actions">
              <button className="ip-btn ghost">Modifica</button>
              <button className="ip-btn">Ritira</button>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}

/* ─────────── MESSAGES (manager) ─────────── */
function MessagesCard() {
  const msgs = [
    { who: "Giulia Wave", init: "GW", verified: false, preview: "Ciao Andrea, ti scrivo perché ho visto il tuo profilo…", time: "8m", unread: true, role: "Artista" },
    { who: "Studio Riva", init: "SR", verified: true, preview: "Confermato: posso lavorare con Luca Bianchi sull'EP a partire da lunedì.", time: "1h", unread: true, role: "Producer" },
    { who: "Martina Rey", init: "MR", verified: true, preview: "Grazie ancora per l'invito! Quando ci sentiamo per parlare di strategie?", time: "3h", unread: true, role: "Roster" },
    { who: "Diego K.", init: "DK", verified: true, preview: "Bel lavoro con Giada, te la rubo per un featuring 😎", time: "Ieri", unread: false, role: "Producer" },
    { who: "Nico Vega", init: "NV", verified: true, preview: "Confermo, mando i preventivi entro stasera.", time: "Lun", unread: false, role: "Producer" },
  ];
  return (
    <div>
      <div className="section-head">
        <div className="t">Messaggi <span className="count">3 da leggere</span></div>
        <a className="more" href="Messaggi.html">Apri chat <ChevIc size={12}/></a>
      </div>
      <div className="card padless">
        <div className="msg-list" style={{ padding: "4px 14px" }}>
          {msgs.map((m, i) => (
            <a key={i} href="Messaggi.html" className={`msg-row ${m.unread ? "unread" : ""}`}>
              <span className="av">{m.init}<span className="online"/></span>
              <div className="body">
                <div className="row1">
                  <span className="name">{m.who}</span>
                  {m.verified && <span className="verified"><MgrIcons.verified size={11}/></span>}
                  <span className={`role-tag ${m.role.toLowerCase()}`}>{m.role}</span>
                </div>
                <div className="preview">{m.preview}</div>
              </div>
              <div className="right">
                <span className="time">{m.time}</span>
                {m.unread && <span className="unread-dot"/>}
              </div>
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ─────────── QUICK ACTIONS ─────────── */
function QuickActions() {
  const actions = [
    { primary: true, t: "Esplora artisti", s: "Scopri talenti emergenti in linea con i tuoi generi gestiti.", ic: <MgrIcons.search size={22}/>, href: "Esplora.html" },
    { t: "Cerca producer", s: "Costruisci la tua rete: producer per i tuoi artisti.", ic: <MgrIcons.mixer size={22}/>, href: "Esplora.html#producer" },
    { t: "Aggiorna profilo", s: "Bio, aree di competenza, link e disponibilità.", ic: <MgrIcons.edit size={22}/>, href: "Profilo.html" },
    { t: "Vedi roster", s: "Activity feed degli artisti che gestisci.", ic: <MgrIcons.users size={22}/>, href: "Roster.html" },
  ];
  return (
    <section>
      <div className="section-head"><div className="t">Azioni rapide</div></div>
      <div className="qa-grid">
        {actions.map((a, i) => (
          <a key={i} href={a.href} className={`qa-card ${a.primary ? "primary" : ""}`}>
            <div className="qa-ic">{a.ic}</div>
            <div className="qa-title">{a.t}</div>
            <div className="qa-sub">{a.s}</div>
            <div className="qa-foot">
              <span>Apri</span>
              <span className="qa-arrow"><ArrIc size={12}/></span>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}

/* ─────────── DISCOVER TALENTS (carousel) ─────────── */
const TALENTS = [
  { id: "t1", name: "Simone Caruso", handle: "@simonecaruso", init: "SC", city: "Torino", genres: ["alt-pop","indie"], match: 92, looking: true, completed: 3, badge: "Active" },
  { id: "t2", name: "Aïda L.", handle: "@aidalow", init: "AL", city: "Milano", genres: ["R&B","neo-soul"], match: 88, looking: true, completed: 8, badge: "Verified" },
  { id: "t3", name: "Theo Marini", handle: "@theomarini", init: "TM", city: "Napoli", genres: ["cantautorato"], match: 84, looking: false, completed: 5, badge: "Active" },
  { id: "t4", name: "Noah Miles", handle: "@noahmiles", init: "NM", city: "Milano", genres: ["indie","alt-pop"], match: 81, looking: false, completed: 12, badge: "Verified" },
  { id: "t5", name: "Vale Frey", handle: "@valefrey", init: "VF", city: "Bologna", genres: ["pop","cantautorato"], match: 78, looking: true, completed: 4, badge: null },
  { id: "t6", name: "Kai Russo", handle: "@kairusso", init: "KR", city: "Roma", genres: ["trap","drill"], match: 76, looking: false, completed: 7, badge: "Active" },
];

function DiscoverTalents() {
  // Pull a curated subset from ESPLORA_ARTISTS if available; fallback to local TALENTS
  const fromEsplora = window.ESPLORA_ARTISTS ? window.ESPLORA_ARTISTS.slice(0, 6).map((a, i) => ({
    id: a.id, name: a.name, handle: a.handle, init: a.init, city: a.city,
    genres: a.genres, match: 92 - i*3, looking: a.looking,
    completed: a.collabs, badge: a.badge,
  })) : TALENTS;
  return (
    <section>
      <div className="section-head">
        <div className="t">
          Talenti da scoprire
          <span className="count">match sui tuoi generi</span>
        </div>
        <a className="more" href="Esplora.html">Vai a Esplora <ChevIc size={12}/></a>
      </div>
      <div className="tal-grid">
        {fromEsplora.map(t => (
          <a key={t.id} href={`Artista.html#id=${t.id}`} className="tal-card">
            <div className="tal-head">
              <span className={`tal-av g${(t.id.charCodeAt(1) % 5) + 1}`}>{t.init}</span>
              <div className="tal-meta">
                <div className="tal-name">{t.name}</div>
                <div className="tal-handle">{t.handle} · {t.city}</div>
              </div>
              <span className="tal-match" title={`Match ${t.match}%`}>{t.match}%</span>
            </div>
            <div className="tal-genres">
              {t.genres.map(g => <span key={g} className="tal-chip">{g}</span>)}
            </div>
            <div className="tal-foot">
              <span className="tal-stat">
                <MgrIcons.audioFile size={11}/>
                {t.completed} collab
              </span>
              {t.badge && <span className={`tal-badge ${t.badge.toLowerCase()}`}>{t.badge}</span>}
              {t.looking && <span className="tal-looking">Cerca manager</span>}
            </div>
            <div className="tal-cta">
              <span>Vedi profilo</span>
              <ArrIc size={12}/>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}

/* ─────────── PROFILE STATS ─────────── */
function ProfileStats() {
  const stats = [
    { l: "Visite profilo", v: "87", d: "+24%", up: true, sub: "ultimi 7gg" },
    { l: "Salvataggi", v: "12", d: "+3", up: true, sub: "nuovi" },
    { l: "DM ricevuti", v: "4", d: "questa sett.", flat: true },
    { l: "Ranking IT", v: "Top 8%", d: "manager alt-pop", flat: true, highlight: true },
  ];
  return (
    <div className="stats-card">
      <div className="section-head" style={{ marginBottom: 4 }}>
        <div className="t">Stats profilo <span className="count">ultimi 7gg</span></div>
        <a className="more" href="Profilo.html">Report <ChevIc size={12}/></a>
      </div>
      <div className="stats-grid">
        {stats.map((s, i) => (
          <div key={i} className={`stat ${s.highlight ? "highlight" : ""}`}>
            <div className="label">{s.l}</div>
            <div className="num">{s.v}</div>
            <div className={`delta ${s.up ? "up" : s.flat ? "flat" : "down"}`}>
              {s.up && <UpIc size={10}/>}
              {s.d}
            </div>
            {s.sub && <div className="stat-sub">{s.sub}</div>}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─────────── PROFILE COMPLETENESS ─────────── */
function ProfileCompleteness() {
  const items = [
    { l: "Foto profilo", done: true, pts: 15 },
    { l: "Bio professionale", done: true, pts: 20 },
    { l: "Aree di competenza", done: true, pts: 15 },
    { l: "Generi gestiti", done: true, pts: 10 },
    { l: "Anni esperienza", done: true, pts: 5 },
    { l: "Link LinkedIn", done: false, pts: 5 },
    { l: "Carica un case study", done: false, pts: 15 },
    { l: "Verifica documento (KYC)", done: false, pts: 15 },
  ];
  const pct = items.reduce((n, i) => n + (i.done ? i.pts : 0), 0);
  const C = 2 * Math.PI * 24;
  const off = C - (pct / 100) * C;
  return (
    <div className="profile-card">
      <div className="profile-head">
        <div className="profile-ring">
          <svg width="56" height="56">
            <circle cx="28" cy="28" r="24" fill="none" stroke="var(--border)" strokeWidth="4"/>
            <circle cx="28" cy="28" r="24" fill="none" stroke="var(--violet)" strokeWidth="4" strokeDasharray={C} strokeDashoffset={off} strokeLinecap="round"/>
          </svg>
          <div className="pct">{pct}%</div>
        </div>
        <div className="meta">
          <div className="t">Completa il profilo</div>
          <div className="s">Profili pieni ricevono il <strong>3× più visite</strong> e appaiono prima nei suggerimenti.</div>
        </div>
      </div>
      <div className="completion-list">
        {items.map((it, i) => (
          <a key={i} href="Profilo.html" className={`completion-item ${it.done ? "done" : ""}`}>
            <span className="check-circle">
              {it.done && <MgrIcons.check size={12}/>}
            </span>
            <span>{it.l}</span>
            <span className="pts">+{it.pts}</span>
            {!it.done && <span className="arrow"><ArrIc size={14}/></span>}
          </a>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, {
  RosterCard, PendingInvites, MessagesCard, QuickActions,
  DiscoverTalents, ProfileStats, ProfileCompleteness, ROSTER, TALENTS,
});
