// SONARA — Producer Wallet & Payout (Revenue · Payout · KYC · Fiscale)
const WIcons = window.SonaraIcons;

/* ─────── ICONS ─────── */
const ArrIc = ({ size = 13 }) => <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>;
const DownloadIc = ({ size = 13 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>;
const CheckIc = ({ size = 12 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>;
const ChevDownIc = ({ size = 11 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>;
const EditIc = ({ size = 13 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>;
const InfoIc = ({ size = 12 }) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>;

/* ─────── REVENUE CHART (mini sparkline area) ─────── */
function RevenueChart({ data, max }) {
  const w = 100, h = 40;
  const points = data.map((v, i) => `${(i / (data.length - 1)) * w},${h - (v / max) * h * 0.9 - 2}`).join(" ");
  const area = `0,${h} ${points} ${w},${h}`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" className="wal-chart">
      <defs>
        <linearGradient id="rev-grad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--violet-bright, #7b55d0)" stopOpacity="0.4"/>
          <stop offset="100%" stopColor="var(--violet-bright, #7b55d0)" stopOpacity="0"/>
        </linearGradient>
      </defs>
      <polygon points={area} fill="url(#rev-grad)"/>
      <polyline points={points} fill="none" stroke="var(--violet-bright, #7b55d0)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" vectorEffect="non-scaling-stroke"/>
    </svg>
  );
}

/* ─────── BAR CHART (30gg revenue) ─────── */
function BarChart({ data }) {
  const max = Math.max(...data.map(d => d.v), 1);
  return (
    <div className="wal-bars">
      {data.map((d, i) => (
        <div key={i} className="wal-bar-col" title={`${d.l}: €${d.v}`}>
          <div className="wal-bar" style={{ height: `${(d.v / max) * 100}%` }}/>
          {i % 5 === 0 && <span className="wal-bar-lbl">{d.l}</span>}
        </div>
      ))}
    </div>
  );
}

/* ─────── TRANSACTIONS ─────── */
const TX = [
  { id: "TX-3201", type: "credit", label: "Vendita beat \"Lupo Solitario\"", who: "RAZZA", whoIn: "RZ", date: "Oggi", net: 39.6, status: "clearance", clearIn: "7gg" },
  { id: "TX-3198", type: "credit", label: "Vendita beat \"Lupo Solitario\"", who: "Yoshi K.", whoIn: "YK", date: "Ieri", net: 39.6, status: "clearance", clearIn: "6gg" },
  { id: "TX-3192", type: "credit", label: "Vendita beat \"Notturno\"", who: "Marco T.", whoIn: "MT", date: "3gg fa", net: 39.6, status: "clearance", clearIn: "4gg" },
  { id: "TX-3186", type: "credit", label: "Ordine completato \"Singolo Bagliore\" — Mix + Master", who: "Giulia P.", whoIn: "GP", date: "4gg fa", net: 158, status: "clearance", clearIn: "3gg" },
  { id: "TX-3180", type: "credit", label: "Vendita beat esclusiva \"Mezzanotte\"", who: "RAZZA", whoIn: "RZ", date: "1 sett. fa", net: 369.6, status: "available" },
  { id: "PY-104", type: "payout", label: "Auto-payout settimanale → IBAN ***4831", date: "Lun 11 maggio", net: -892, status: "paid", receipt: true },
  { id: "TX-3175", type: "credit", label: "Vendita beat \"Asfalto Bagnato\"", who: "Federico V.", whoIn: "FV", date: "9gg fa", net: 44, status: "available" },
  { id: "TX-3170", type: "credit", label: "Ordine completato \"Beat su brief Tramonto\" — Custom production", who: "Federico V.", whoIn: "FV", date: "11gg fa", net: 308, status: "available" },
  { id: "PY-103", type: "payout", label: "Auto-payout settimanale → IBAN ***4831", date: "Lun 4 maggio", net: -643, status: "paid", receipt: true },
  { id: "TX-3162", type: "fee", label: "Fee Sonara su ordine ORD-4780", date: "2 sett. fa", net: -15, status: "applied" },
];

/* ─────── PAYOUTS HISTORY ─────── */
const PAYOUTS = [
  { id: "PY-104", date: "11 maggio 2026", amount: 892, iban: "IT60 X054 2811 1010 0000 0**4 831", status: "paid" },
  { id: "PY-103", date: "4 maggio 2026", amount: 643, iban: "IT60 X054 2811 1010 0000 0**4 831", status: "paid" },
  { id: "PY-102", date: "27 aprile 2026", amount: 1120, iban: "IT60 X054 2811 1010 0000 0**4 831", status: "paid" },
  { id: "PY-101", date: "20 aprile 2026", amount: 487, iban: "IT60 X054 2811 1010 0000 0**4 831", status: "paid" },
  { id: "PY-100", date: "13 aprile 2026", amount: 920, iban: "IT60 X054 2811 1010 0000 0**4 831", status: "paid" },
];

/* ─────── PAGE ─────── */
function WalletPage() {
  const [tab, setTab] = React.useState("overview");
  const [txFilter, setTxFilter] = React.useState("all");

  // mock 30d barchart data
  const bars = Array.from({ length: 30 }, (_, i) => ({
    l: `${i + 1}`,
    v: Math.round(Math.abs(Math.sin(i * 0.7) * 80 + (i % 7 === 0 ? 200 : 60) + Math.random() * 40)),
  }));

  const sparkData = [220, 280, 180, 340, 290, 480, 540, 410, 620, 700, 580, 720];

  return (
    <main className="page" data-screen-label="Wallet Producer">
      <div className="cat-head">
        <div className="cat-head-l">
          <h1 className="cat-h1">Wallet & payout</h1>
          <div className="cat-head-stats">
            <span>Auto-payout settimanale</span>
            <span className="sep">·</span>
            <span>IBAN ***4831</span>
            <span className="sep">·</span>
            <span style={{ color: "#16a34a" }}>● KYC verificato</span>
          </div>
        </div>
        <div className="cat-head-actions">
          <button className="pf-action-btn"><DownloadIc size={13}/> Esporta CSV</button>
          <button className="pf-action-btn primary"><ArrIc size={13}/> Richiedi payout</button>
        </div>
      </div>

      <div className="cat-tabs">
        <button className={`cat-tab ${tab === "overview" ? "active" : ""}`} onClick={() => setTab("overview")}>Panoramica</button>
        <button className={`cat-tab ${tab === "transactions" ? "active" : ""}`} onClick={() => setTab("transactions")}>Transazioni</button>
        <button className={`cat-tab ${tab === "payouts" ? "active" : ""}`} onClick={() => setTab("payouts")}>Storico payout</button>
        <button className={`cat-tab ${tab === "settings" ? "active" : ""}`} onClick={() => setTab("settings")}>Impostazioni & KYC</button>
      </div>

      {tab === "overview" && (
        <>
          {/* TOP BALANCE CARDS */}
          <div className="wal-top">
            <div className="wal-balance-card">
              <div className="wal-balance-label">Disponibile per payout</div>
              <div className="wal-balance">
                <span className="ccy">€</span>
                <span className="num">1.247</span>
                <span className="cents">,60</span>
              </div>
              <div className="wal-balance-sub">
                Prossimo auto-payout <strong>lunedì 18 maggio</strong> · puoi anticipare on-demand
              </div>
              <div className="wal-balance-acts">
                <button className="ord-btn primary"><ArrIc size={12}/> Richiedi payout</button>
                <button className="ord-btn">Sposta su carta virtuale</button>
              </div>
              <RevenueChart data={sparkData} max={Math.max(...sparkData)}/>
            </div>

            <div className="wal-side">
              <div className="wal-mini-card escrow">
                <div className="wal-mini-l"><span className="wal-mini-dot esc"/> In escrow</div>
                <div className="wal-mini-v">€<strong>892</strong>,00</div>
                <div className="wal-mini-s">3 ordini · si liberano alla consegna</div>
              </div>
              <div className="wal-mini-card clearance">
                <div className="wal-mini-l"><span className="wal-mini-dot clr"/> In clearance</div>
                <div className="wal-mini-v">€<strong>340</strong>,00</div>
                <div className="wal-mini-s">Protezione chargeback · 7gg</div>
              </div>
              <div className="wal-mini-card lifetime">
                <div className="wal-mini-l"><span className="wal-mini-dot lif"/> Lifetime</div>
                <div className="wal-mini-v">€<strong>4.120</strong>,00</div>
                <div className="wal-mini-s">47 ordini · membro da gennaio 2023</div>
              </div>
            </div>
          </div>

          {/* 30gg revenue chart */}
          <section className="wal-section">
            <div className="wal-section-head">
              <div className="wal-section-title">Revenue ultimi 30gg</div>
              <div className="wal-section-stats">
                <span>Totale <strong>€2.140</strong></span>
                <span className="up"><UpIc size={11}/> +24% vs prec.</span>
              </div>
            </div>
            <BarChart data={bars}/>
            <div className="wal-section-foot">
              <span>Media giornaliera <strong>€71,30</strong></span>
              <span className="sep">·</span>
              <span>Picco <strong>€340</strong> il 24 aprile (vendita esclusiva)</span>
              <span className="sep">·</span>
              <span>Min <strong>€0</strong> · 3 giorni senza vendite</span>
            </div>
          </section>

          {/* breakdown source */}
          <section className="wal-section">
            <div className="wal-section-head">
              <div className="wal-section-title">Da dove arriva la revenue</div>
              <div className="wal-section-stats">
                <span>Ultimi 30gg</span>
              </div>
            </div>
            <div className="wal-source">
              <div className="wal-source-row">
                <div className="wal-source-bar" style={{ "--p": "44%", "--c": "#7b55d0" }}/>
                <div className="wal-source-meta">
                  <div className="t">Servizi mix/master</div>
                  <div className="s">7 ordini chiusi · ticket medio €135</div>
                </div>
                <div className="wal-source-v">€945</div>
              </div>
              <div className="wal-source-row">
                <div className="wal-source-bar" style={{ "--p": "32%", "--c": "#f59e0b" }}/>
                <div className="wal-source-meta">
                  <div className="t">Beat esclusivo</div>
                  <div className="s">1 vendita · esclusiva "Mezzanotte"</div>
                </div>
                <div className="wal-source-v">€680</div>
              </div>
              <div className="wal-source-row">
                <div className="wal-source-bar" style={{ "--p": "16%", "--c": "#0ea5e9" }}/>
                <div className="wal-source-meta">
                  <div className="t">Custom production</div>
                  <div className="s">1 ordine completato</div>
                </div>
                <div className="wal-source-v">€340</div>
              </div>
              <div className="wal-source-row">
                <div className="wal-source-bar" style={{ "--p": "8%", "--c": "#16a34a" }}/>
                <div className="wal-source-meta">
                  <div className="t">Beat non-esclusivi</div>
                  <div className="s">5 vendite · ticket medio €35</div>
                </div>
                <div className="wal-source-v">€175</div>
              </div>
            </div>
          </section>
        </>
      )}

      {tab === "transactions" && (
        <>
          <div className="off-toolbar">
            <div className="ord-chips" style={{ margin: 0 }}>
              {[
                { v: "all", l: "Tutte" },
                { v: "credit", l: "Entrate" },
                { v: "payout", l: "Payout" },
                { v: "fee", l: "Fee Sonara" },
              ].map(c => (
                <button key={c.v} className={`cat-chip ${txFilter === c.v ? "active" : ""}`} onClick={() => setTxFilter(c.v)}>{c.l}</button>
              ))}
            </div>
            <button className="pf-action-btn"><DownloadIc size={13}/> Esporta CSV</button>
          </div>

          <div className="wal-tx-list">
            {TX.filter(t => txFilter === "all" || t.type === txFilter).map(t => (
              <div className={`wal-tx ${t.type}`} key={t.id}>
                <div className="wal-tx-ic">
                  {t.type === "credit" && <ArrIc size={14}/>}
                  {t.type === "payout" && <DownloadIc size={14}/>}
                  {t.type === "fee" && <span style={{ fontSize: 14, fontWeight: 700 }}>%</span>}
                </div>
                <div className="wal-tx-body">
                  <div className="wal-tx-row1">
                    <div className="wal-tx-label">{t.label}</div>
                    <div className={`wal-tx-amt ${t.net > 0 ? "pos" : "neg"}`}>
                      {t.net > 0 ? "+" : "−"} €{Math.abs(t.net).toFixed(2).replace(".", ",")}
                    </div>
                  </div>
                  <div className="wal-tx-row2">
                    <span className="wal-tx-id">{t.id}</span>
                    <span className="sep">·</span>
                    <span>{t.date}</span>
                    {t.who && (
                      <>
                        <span className="sep">·</span>
                        <span className="wal-tx-who"><span className="off-av sm">{t.whoIn}</span> {t.who}</span>
                      </>
                    )}
                    <span className="sep">·</span>
                    {t.status === "available" && <span className="ord-status ok">Disponibile</span>}
                    {t.status === "clearance" && <span className="ord-status warn">In clearance · {t.clearIn}</span>}
                    {t.status === "paid" && <span className="ord-status ok"><CheckIc size={11}/> Pagato</span>}
                    {t.status === "applied" && <span className="ord-status neutral">Applicata</span>}
                  </div>
                </div>
                {t.receipt && (
                  <button className="cat-icon-btn" title="Scarica ricevuta"><DownloadIc size={13}/></button>
                )}
              </div>
            ))}
          </div>
        </>
      )}

      {tab === "payouts" && (
        <div className="cat-table">
          <div className="cat-table-head" style={{ gridTemplateColumns: "minmax(0, 1fr) 200px 250px 110px 80px" }}>
            <div className="cat-td">ID payout</div>
            <div className="cat-td">Data esecuzione</div>
            <div className="cat-td">IBAN</div>
            <div className="cat-td cat-td-num">Importo</div>
            <div className="cat-td"></div>
          </div>
          {PAYOUTS.map(p => (
            <div className="cat-tr" key={p.id} style={{ gridTemplateColumns: "minmax(0, 1fr) 200px 250px 110px 80px", cursor: "default" }}>
              <div className="cat-td">
                <div className="cat-tr-title" style={{ fontFamily: "var(--font-mono)", fontSize: 13 }}>{p.id}</div>
                <div className="cat-tr-meta">Auto-payout settimanale</div>
              </div>
              <div className="cat-td">{p.date}</div>
              <div className="cat-td" style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>{p.iban}</div>
              <div className="cat-td cat-td-num strong">€{p.amount.toFixed(2).replace(".", ",")}</div>
              <div className="cat-td cat-td-actions">
                <button className="cat-icon-btn" title="Scarica ricevuta"><DownloadIc size={13}/></button>
              </div>
            </div>
          ))}
        </div>
      )}

      {tab === "settings" && <SettingsTab/>}
    </main>
  );
}

/* ─────── SETTINGS / KYC ─────── */
function SettingsTab() {
  return (
    <div className="wal-settings">
      {/* KYC SUMMARY */}
      <section className="pf-panel">
        <header className="pf-panel-head">
          <div className="pf-panel-title">Stato KYC</div>
          <span className="ord-status ok"><CheckIc size={11}/> Verificato</span>
        </header>
        <div className="wal-kyc-flow">
          {[
            { l: "Tipologia", v: "P.IVA forfettario", done: true },
            { l: "Dati anagrafici", v: "Vega Nicolò · 21/03/1992", done: true },
            { l: "Documento", v: "Carta d'identità AX1234567 · verificata", done: true },
            { l: "Dati fiscali", v: "P.IVA 04598720963 · regime forfettario", done: true },
            { l: "IBAN payout", v: "IT60 X054 2811 1010 0000 0**4 831 · verificato", done: true },
          ].map((s, i) => (
            <div key={i} className={`wal-kyc-step ${s.done ? "done" : ""}`}>
              <span className="wal-kyc-num">{s.done ? <CheckIc size={13}/> : i + 1}</span>
              <div className="wal-kyc-meta">
                <div className="l">{s.l}</div>
                <div className="v">{s.v}</div>
              </div>
              <button className="cat-icon-btn"><EditIc size={13}/></button>
            </div>
          ))}
        </div>
      </section>

      <section className="pf-panel">
        <header className="pf-panel-head">
          <div className="pf-panel-title">Preferenze payout</div>
        </header>
        <div className="wal-prefs">
          <div className="wal-pref-row">
            <div className="meta">
              <div className="t">Auto-payout settimanale</div>
              <div className="s">Ogni lunedì viene eseguito il payout di tutti i fondi disponibili</div>
            </div>
            <button className="pf-switch on"/>
          </div>
          <div className="wal-pref-row">
            <div className="meta">
              <div className="t">Soglia minima on-demand</div>
              <div className="s">Importo minimo per payout su richiesta · default €20</div>
            </div>
            <input className="pf-input" defaultValue="20" style={{ width: 100, textAlign: "right" }}/>
          </div>
          <div className="wal-pref-row">
            <div className="meta">
              <div className="t">Notifiche payout</div>
              <div className="s">Email + push quando payout viene eseguito</div>
            </div>
            <button className="pf-switch on"/>
          </div>
        </div>
      </section>

      <section className="pf-panel">
        <header className="pf-panel-head">
          <div className="pf-panel-title">Dati fiscali</div>
          <button className="ord-btn ghost"><EditIc size={12}/> Modifica</button>
        </header>
        <div className="wal-fiscal">
          <div className="wal-fiscal-row">
            <span className="l">Tipologia</span>
            <span className="v">P.IVA forfettario</span>
          </div>
          <div className="wal-fiscal-row">
            <span className="l">Ragione sociale</span>
            <span className="v">Nicolò Vega</span>
          </div>
          <div className="wal-fiscal-row">
            <span className="l">P.IVA</span>
            <span className="v">04598720963</span>
          </div>
          <div className="wal-fiscal-row">
            <span className="l">Codice fiscale</span>
            <span className="v">VGENCL92C21F205K</span>
          </div>
          <div className="wal-fiscal-row">
            <span className="l">Codice SDI</span>
            <span className="v">5RUO82D</span>
          </div>
          <div className="wal-fiscal-row">
            <span className="l">Indirizzo</span>
            <span className="v">Via Tortona 32 · 20144 Milano (MI)</span>
          </div>
          <div className="wal-fiscal-note">
            <InfoIc size={12}/>
            Sonara emette ricevuta marketplace mensile per la fee. Per ogni ordine emetti tu fattura al cliente — la trovi pronta nello storico.
          </div>
        </div>
      </section>

      <section className="pf-panel">
        <header className="pf-panel-head">
          <div className="pf-panel-title">Conto bancario</div>
        </header>
        <div className="wal-iban">
          <div className="wal-iban-card">
            <div className="wal-iban-bank">UniCredit · primario</div>
            <div className="wal-iban-num">IT60 X054 2811 1010 0000 0**4 831</div>
            <div className="wal-iban-meta">
              <span className="ord-status ok"><CheckIc size={11}/> Verificato</span>
              <span>Verifica il 18 feb 2024</span>
            </div>
            <div className="wal-iban-acts">
              <button className="ord-btn ghost">Modifica IBAN</button>
              <button className="ord-btn ghost">Aggiungi secondario</button>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

window.WalletPage = WalletPage;
