// SONARA — Producer Nav (sidebar + topbar + bottomnav)
// Persona: Nico Vega / @nicovega — Milano, trap/hip-hop producer.
const PIcons = window.SonaraIcons;

function Sidebar({ active = "home" }) {
  const marketplace = { key: "opportunita", label: "Opportunità", icon: <PIcons.target size={18}/>, badge: 8, href: "Opportunita.html" };
  const work = [
    { key: "home", label: "Home", icon: <PIcons.equalizer size={18}/>, href: "Dashboard.html" },
    { key: "catalog", label: "Catalog", icon: <PIcons.disc size={18}/>, href: "Catalog.html" },
    { key: "ordini", label: "Ordini", icon: <PIcons.audioFile size={18}/>, badge: 4, href: "Ordini.html" },
    { key: "messaggi", label: "Messaggi", icon: <PIcons.connect size={18}/>, badge: 3, href: "Messaggi.html" },
  ];
  const market = [
    { key: "esplora", label: "Esplora marketplace", icon: <PIcons.search size={18}/>, href: "Esplora.html" },
  ];
  const biz = [
    { key: "wallet", label: "Wallet & payout", icon: <PIcons.coins size={18}/>, href: "Wallet.html" },
    { key: "profilo", label: "Profilo pubblico", icon: <PIcons.user size={18}/>, href: "Profilo.html" },
  ];
  return (
    <aside className="sidebar">
      <a href="Dashboard.html" className="sidebar-logo">
        <span className="mark"><PIcons.soundwaveLogo size={16}/></span>
        <span className="sidebar-logo-text">Sonara</span>
        <window.SidebarToggle/>
      </a>

      <div className="sidebar-section accent">
        <span className="sidebar-section-dot"/>
        Marketplace
      </div>
      <a href={marketplace.href} className={`nav-item market ${active === marketplace.key ? "active" : ""}`}>
        <span className="ic">{marketplace.icon}</span>
        <span className="market-meta">
          <span className="label">{marketplace.label}</span>
          <span className="sub">{marketplace.badge} richieste open per te</span>
        </span>
        {marketplace.badge && <span className="badge-pill new">{marketplace.badge}</span>}
      </a>

      <div className="sidebar-section">Il tuo lavoro</div>
      {work.map(i => (
        <a key={i.key} href={i.href} className={`nav-item ${active === i.key ? "active" : ""}`}>
          <span className="ic">{i.icon}</span>
          {i.label}
          {i.badge && <span className="badge-pill">{i.badge}</span>}
        </a>
      ))}

      <div className="sidebar-section">Esplora</div>
      {market.map(i => (
        <a key={i.key} href={i.href} className={`nav-item ${active === i.key ? "active" : ""}`}>
          <span className="ic">{i.icon}</span>
          {i.label}
        </a>
      ))}

      <div className="sidebar-section">I tuoi affari</div>
      {biz.map(i => (
        <a key={i.key} href={i.href} className={`nav-item ${active === i.key ? "active" : ""}`}>
          <span className="ic">{i.icon}</span>
          {i.label}
        </a>
      ))}

      <div className="sidebar-foot">
        <span className="av">NV</span>
        <div className="meta">
          <div className="n">Nico Vega</div>
          <div className="h">@nicovega · Producer</div>
        </div>
      </div>
    </aside>
  );
}

function Topbar({
  available = "1.247",
  kyc = "verified", // "verified" | "in_review" | "incomplete"
  theme = "dark",
  onToggleTheme,
}) {
  const [notifOpen, setNotifOpen] = React.useState(false);
  const notifRef = React.useRef(null);
  React.useEffect(() => {
    const onDown = (e) => {
      if (notifOpen && notifRef.current && !notifRef.current.contains(e.target)) setNotifOpen(false);
    };
    document.addEventListener("mousedown", onDown);
    return () => document.removeEventListener("mousedown", onDown);
  }, [notifOpen]);

  const SunIcon = ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="M4.93 4.93l1.41 1.41"/><path d="M17.66 17.66l1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="M4.93 19.07l1.41-1.41"/><path d="M17.66 6.34l1.41-1.41"/>
    </svg>
  );
  const MoonIcon = ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
    </svg>
  );

  const kycMeta = kyc === "verified"
    ? { label: "KYC ok", cls: "ok", ic: <PIcons.shield size={12}/> }
    : kyc === "in_review"
    ? { label: "KYC in review", cls: "warn", ic: <PIcons.shield size={12}/> }
    : { label: "Completa KYC", cls: "alert", ic: <PIcons.shield size={12}/> };

  return (
    <header className="topbar">
      <div className="search-box">
        <PIcons.search size={16}/>
        <input placeholder="Cerca ordini, clienti, beat…"/>
        <span className="kbd">⌘ K</span>
      </div>
      <div className="spacer"/>
      <a href="Opportunita.html" className="opp-cta-pill" title="Sfoglia opportunità aperte">
        <span className="opp-cta-ic"><PIcons.target size={13}/></span>
        <span className="opp-cta-label">Opportunità</span>
        <span className="opp-cta-badge">8 nuove</span>
      </a>
      <a href="Feed.html" className="feed-pill has-new" title="3 nuovi nel Feed">
        <span className="ic"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 11a9 9 0 0 1 9 9"/><path d="M4 4a16 16 0 0 1 16 16"/><circle cx="5" cy="19" r="1"/></svg></span>
        <span>Feed</span>
        <span className="new-dot">3</span>
      </a>
      <button className="icon-btn" title={theme === "dark" ? "Passa a light" : "Passa a dark"} onClick={onToggleTheme}>
        {theme === "dark" ? <SunIcon size={16}/> : <MoonIcon size={16}/>}
      </button>
      <div className="notif-wrap" ref={notifRef}>
        <button className={`icon-btn ${notifOpen ? "active" : ""}`} title="Notifiche" onClick={() => setNotifOpen(o => !o)}>
          <PIcons.bell size={16}/>
          <span className="dot-notif"/>
        </button>
        {notifOpen && <NotificationsPanel onClose={() => setNotifOpen(false)}/>}
      </div>
      <button className="avatar-btn">NV</button>
    </header>
  );
}

function Greet({
  name = "Nico",
  sub = "3 ordini in coda, 2 da consegnare oggi. €1.247 disponibili per payout.",
}) {
  return (
    <div className="greet">
      <div>
        <h1 className="hello">Ciao, <span className="name">{name}</span> 👋</h1>
        <div className="sub">{sub}</div>
      </div>
      <div className="right">
        <a href="CaricaBeat.html" className="wallet-pill">
          <PIcons.disc size={14}/>
          <span className="num" style={{ fontSize: 13 }}>Carica beat</span>
        </a>
        <a href="CreaListing.html" className="cta-pill">
          <PIcons.mixer size={14}/>
          Crea listing
        </a>
      </div>
    </div>
  );
}

function BottomNav({ active = "home" }) {
  const items = [
    { key: "home", label: "Home", icon: <PIcons.equalizer size={20}/>, href: "Dashboard.html" },
    { key: "opportunita", label: "Opp.", icon: <PIcons.target size={20}/>, badge: 8, href: "Opportunita.html", primary: true },
    { key: "esplora", label: "Esplora", icon: <PIcons.search size={20}/>, href: "Esplora.html" },
    { key: "ordini", label: "Ordini", icon: <PIcons.audioFile size={20}/>, badge: 4, href: "Ordini.html" },
    { key: "chat", label: "Chat", icon: <PIcons.connect size={20}/>, badge: 3, href: "Messaggi.html" },
  ];
  return (
    <nav className="bottom-nav">
      {items.map(i => (
        <a key={i.key} href={i.href} className={`bottom-nav-item ${active === i.key ? "active" : ""} ${i.primary ? "primary" : ""}`}>
          <span className="ic">{i.icon}</span>
          {i.label}
          {i.badge && <span className="badge-pill">{i.badge}</span>}
        </a>
      ))}
    </nav>
  );
}

Object.assign(window, { Sidebar, Topbar, Greet, BottomNav });

/* ─────────────────────────────────────────────────── */
/* Notifications panel (popover)                       */
/* ─────────────────────────────────────────────────── */

const NOTIFICATIONS = [
  {
    id: "n1", type: "order", unread: true, time: "8m fa",
    title: "Nuovo ordine ricevuto",
    body: "RAZZA ha richiesto Mix + Master per l'EP \"Asfalto\" · €180",
    href: "Ordine.html",
    icon: "audioFile", accent: "violet",
  },
  {
    id: "n2", type: "deadline", unread: true, time: "1h fa", urgent: true,
    title: "Scadenza imminente",
    body: "ORD-4821 \"EP Asfalto\" scade tra 22h. Carica la v2.",
    href: "Ordine.html",
    icon: "clock", accent: "warning",
  },
  {
    id: "n3", type: "counter", unread: true, time: "3h fa",
    title: "Counter-offer ricevuto",
    body: "AlessioRap ti contro-offre €140 invece di €180 su REQ-9214",
    href: "Ordini.html",
    icon: "target", accent: "violet",
  },
  {
    id: "n4", type: "saved_search", unread: false, time: "5h fa",
    title: "Match dalla tua ricerca salvata",
    body: "3 nuove richieste matchano \"Trap Milano premium\"",
    href: "Opportunita.html",
    icon: "bell", accent: "violet",
  },
  {
    id: "n5", type: "review", unread: false, time: "Ieri",
    title: "Nuova recensione 5★",
    body: "Yoshi K. ti ha lasciato una recensione su \"Co-prod Quartiere\"",
    href: "Profilo.html",
    icon: "star", accent: "gold",
  },
  {
    id: "n6", type: "payout", unread: false, time: "Lun 11 mag",
    title: "Payout eseguito",
    body: "€892,00 inviati sul tuo IBAN ***4831. Arrivo previsto in 1-2 gg lavorativi.",
    href: "Wallet.html",
    icon: "coins", accent: "success",
  },
  {
    id: "n7", type: "sale", unread: false, time: "12 mag",
    title: "Beat venduto",
    body: "Marco T. ha acquistato \"Notturno\" · +€39,60 in wallet",
    href: "Catalog.html",
    icon: "disc", accent: "success",
  },
  {
    id: "n8", type: "system", unread: false, time: "10 mag",
    title: "Aggiornamento policy",
    body: "Abbiamo aggiornato i Termini di Servizio. Leggi le novità.",
    href: "Profilo.html",
    icon: "shield", accent: "neutral",
  },
];

function NotificationsPanel({ onClose }) {
  const [filter, setFilter] = React.useState("all"); // all | unread
  const unreadCount = NOTIFICATIONS.filter(n => n.unread).length;
  const items = filter === "unread" ? NOTIFICATIONS.filter(n => n.unread) : NOTIFICATIONS;

  return (
    <div className="notif-panel">
      <header className="notif-head">
        <div className="notif-title">
          Notifiche
          {unreadCount > 0 && <span className="notif-title-badge">{unreadCount} nuove</span>}
        </div>
        <button className="notif-mark-all">Segna tutte come lette</button>
      </header>
      <div className="notif-tabs">
        <button className={`notif-tab ${filter === "all" ? "active" : ""}`} onClick={() => setFilter("all")}>
          Tutte <span className="c">{NOTIFICATIONS.length}</span>
        </button>
        <button className={`notif-tab ${filter === "unread" ? "active" : ""}`} onClick={() => setFilter("unread")}>
          Non lette <span className="c">{unreadCount}</span>
        </button>
      </div>
      <div className="notif-list">
        {items.map(n => {
          const Ic = PIcons[n.icon] || PIcons.bell;
          return (
            <a key={n.id} href={n.href} className={`notif-item ${n.unread ? "unread" : ""}`} onClick={onClose}>
              <span className={`notif-ic ${n.accent} ${n.urgent ? "urgent" : ""}`}>
                <Ic size={14}/>
              </span>
              <div className="notif-body">
                <div className="notif-row1">
                  <span className="notif-item-title">{n.title}</span>
                  <span className="notif-time">{n.time}</span>
                </div>
                <div className="notif-text">{n.body}</div>
              </div>
              {n.unread && <span className="notif-unread-dot"/>}
            </a>
          );
        })}
        {items.length === 0 && (
          <div className="notif-empty">
            <PIcons.bell size={22}/>
            <div className="t">Nessuna notifica non letta</div>
            <div className="s">Sei in pari 🎉</div>
          </div>
        )}
      </div>
      <footer className="notif-foot">
        <a href="Profilo.html" className="notif-foot-link">Impostazioni notifiche</a>
        <a href="Feed.html" className="notif-foot-link">Vedi tutte</a>
      </footer>
    </div>
  );
}

window.NotificationsPanel = NotificationsPanel;
