// SONARA — Wallet page (artista)
const WIcons = window.SonaraIcons;

// ============= DATA =============
const TX_DATA = [
  { id: "tx-001", date: "Oggi, 14:32", day: "Oggi", kind: "out", icon: "service", label: "Mix Pro · Marco Vega", sub: "Ordine #SV-4821", amount: "-€189,00", badge: "escrow" },
  { id: "tx-002", date: "Oggi, 09:15", day: "Oggi", kind: "in", icon: "topup", label: "Ricarica wallet", sub: "Visa •• 4242", amount: "+€100,00", badge: null },
  { id: "tx-003", date: "Ieri, 22:04", day: "Ieri", kind: "out", icon: "beat", label: "Beat 'Lunar Drift'", sub: "Producer @luxx · Licenza non-esclusiva", amount: "-€49,00", badge: null },
  { id: "tx-004", date: "Ieri, 18:30", day: "Ieri", kind: "refund", icon: "refund", label: "Rimborso ordine #SV-4810", sub: "Annullamento da producer · accreditato in saldo", amount: "+€85,00", badge: "refunded" },
  { id: "tx-005", date: "12 mag, 11:20", day: "12 maggio", kind: "out", icon: "beat", label: "Beat 'Tokyo Nights'", sub: "Producer @808king · Licenza non-esclusiva", amount: "-€39,00", badge: null },
  { id: "tx-006", date: "10 mag, 16:48", day: "10 maggio", kind: "out", icon: "service", label: "Vocal production · Sara K.", sub: "Ordine #SV-4789 · Completato", amount: "-€220,00", badge: null },
  { id: "tx-007", date: "08 mag, 09:00", day: "08 maggio", kind: "in", icon: "topup", label: "Ricarica wallet", sub: "Apple Pay", amount: "+€250,00", badge: null },
  { id: "tx-008", date: "05 mag, 12:14", day: "05 maggio", kind: "out", icon: "service", label: "Mastering · Hearfield Studio", sub: "Ordine #SV-4756 · In escrow", amount: "-€95,00", badge: "escrow" },
  { id: "tx-009", date: "01 mag, 19:32", day: "01 maggio", kind: "in", icon: "promo", label: "Bonus benvenuto", sub: "Welcome credit · accreditato in saldo", amount: "+€10,00", badge: null },
];

const METHODS_DATA = [
  { id: "m1", brand: "visa", last4: "4242", name: "Luca Marini", exp: "07 / 27", isDefault: true },
  { id: "m2", brand: "mc", last4: "8821", name: "Luca Marini", exp: "11 / 25", isDefault: false, expiringSoon: true },
  { id: "m3", brand: "applepay", last4: null, name: "Apple Pay · iPhone 15", exp: null, isDefault: false },
];

const DOCS_DATA = [
  { id: "d1", name: "Estratto conto · Maggio 2025", size: "PDF · 124 KB" },
  { id: "d2", name: "Estratto conto · Aprile 2025", size: "PDF · 118 KB" },
  { id: "d3", name: "Esporta tutto (CSV)", size: "Tutte le transazioni" },
];

// ============= ICONS =============
const TxKindIcon = ({ kind }) => {
  if (kind === "topup") return <WIcons.coins size={16}/>;
  if (kind === "promo") return <WIcons.zap size={16}/>;
  if (kind === "refund") return <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-15-6.7L3 13"/></svg>;
  if (kind === "service") return <WIcons.audioFile size={16}/>;
  if (kind === "beat") return <WIcons.disc size={16}/>;
  return <WIcons.coins size={16}/>;
};

const ChevronRight = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 18l6-6-6-6"/></svg>
);

const PlusIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M5 12h14"/></svg>
);

const DownloadIcon = ({ size = 16 }) => (
  <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 FileIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
);

const InfoIcon = ({ size = 18 }) => (
  <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>
);

const DotsIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></svg>
);

// ============= HERO =============
function WalletHero({ onTopup }) {
  return (
    <section className="w-hero">
      <div className="w-hero-grid">
        <div className="w-hero-left">
          <div className="w-hero-label">
            <span className="dot"/>
            Saldo wallet
          </div>
          <div className="w-balance">
            <span className="ccy">€</span>
            <span>425</span>
            <span className="cents">,00</span>
          </div>
          <div className="w-hero-meta">
            <span className="chip">di cui <strong>€10</strong> bonus benvenuto</span>
            <span className="chip">€189 in escrow su 1 ordine</span>
          </div>
        </div>
        <div className="w-hero-actions">
          <button className="w-btn w-btn-primary" onClick={onTopup}>
            <PlusIcon size={16}/>
            Ricarica wallet
          </button>
          <button className="w-btn w-btn-secondary">
            <DownloadIcon size={14}/>
            Esporta
          </button>
        </div>
      </div>

      <div className="w-spend">
        <div className="w-spend-item">
          <div className="l">Speso 30gg</div>
          <div className="v"><span className="ccy">€</span>592</div>
          <div className="d neg">+18% vs mese scorso</div>
        </div>
        <div className="w-spend-item">
          <div className="l">Ricaricato 30gg</div>
          <div className="v"><span className="ccy">€</span>350</div>
          <div className="d">3 ricariche</div>
        </div>
        <div className="w-spend-item">
          <div className="l">In escrow</div>
          <div className="v"><span className="ccy">€</span>189</div>
          <div className="d">su 1 ordine attivo</div>
        </div>
      </div>
    </section>
  );
}

// ============= TX LIST =============
function TxRow({ tx }) {
  const kindClass = tx.kind === "in" ? "in" : tx.kind === "refund" ? "refund" : tx.kind === "out" && tx.badge === "escrow" ? "escrow" : "out";
  const amountClass = tx.kind === "in" ? "in" : tx.kind === "refund" ? "refund" : "out";
  return (
    <div className="w-tx" role="button" tabIndex={0}>
      <div className={`w-tx-icon ${kindClass}`}>
        <TxKindIcon kind={tx.icon}/>
      </div>
      <div className="w-tx-body">
        <div className="w-tx-row1">
          <span className="label">{tx.label}</span>
          {tx.badge === "escrow" && <span className="badge escrow">In escrow</span>}
          {tx.badge === "refunded" && <span className="badge refunded">Rimborsato</span>}
          {tx.badge === "pending" && <span className="badge pending">In sospeso</span>}
        </div>
        <div className="w-tx-row2">
          <span>{tx.sub}</span>
          <span className="sep">·</span>
          <span>{tx.date}</span>
        </div>
      </div>
      <div className={`w-tx-amount ${amountClass}`}>{tx.amount}</div>
      <div className="w-tx-arrow"><ChevronRight size={16}/></div>
    </div>
  );
}

function TxPanel() {
  const [filter, setFilter] = React.useState("all");

  const filtered = React.useMemo(() => {
    if (filter === "all") return TX_DATA;
    if (filter === "in") return TX_DATA.filter(t => t.kind === "in");
    if (filter === "out") return TX_DATA.filter(t => t.kind === "out");
    if (filter === "refund") return TX_DATA.filter(t => t.kind === "refund");
    return TX_DATA;
  }, [filter]);

  // Group by day
  const grouped = React.useMemo(() => {
    const groups = [];
    let current = null;
    filtered.forEach(tx => {
      if (!current || current.day !== tx.day) {
        current = { day: tx.day, items: [] };
        groups.push(current);
      }
      current.items.push(tx);
    });
    return groups;
  }, [filtered]);

  const counts = React.useMemo(() => ({
    all: TX_DATA.length,
    in: TX_DATA.filter(t => t.kind === "in").length,
    out: TX_DATA.filter(t => t.kind === "out").length,
    refund: TX_DATA.filter(t => t.kind === "refund").length,
  }), []);

  return (
    <section className="w-panel">
      <div className="w-panel-head">
        <div className="w-panel-title">
          Transazioni
          <span className="count">{filtered.length}</span>
        </div>
        <div className="w-filters" role="tablist">
          <button className={`w-filter ${filter === "all" ? "active" : ""}`} onClick={() => setFilter("all")}>
            Tutte <span className="num">{counts.all}</span>
          </button>
          <button className={`w-filter ${filter === "in" ? "active" : ""}`} onClick={() => setFilter("in")}>
            Ricariche <span className="num">{counts.in}</span>
          </button>
          <button className={`w-filter ${filter === "out" ? "active" : ""}`} onClick={() => setFilter("out")}>
            Acquisti <span className="num">{counts.out}</span>
          </button>
          <button className={`w-filter ${filter === "refund" ? "active" : ""}`} onClick={() => setFilter("refund")}>
            Refund <span className="num">{counts.refund}</span>
          </button>
        </div>
      </div>

      {filtered.length === 0 ? (
        <div className="w-empty">
          <div className="ic"><WIcons.coins size={20}/></div>
          Nessuna transazione in questa categoria.
        </div>
      ) : (
        grouped.map(g => (
          <React.Fragment key={g.day}>
            <div className="w-day">{g.day}</div>
            {g.items.map(tx => <TxRow key={tx.id} tx={tx}/>)}
          </React.Fragment>
        ))
      )}

      <div className="w-panel-foot">
        <span>Mostrate ultime 30 transazioni</span>
        <a href="#" onClick={(e) => e.preventDefault()}>Carica altre →</a>
      </div>
    </section>
  );
}

// ============= METHODS =============
function MethodRow({ m }) {
  return (
    <div className="w-method">
      <div className={`w-card-art ${m.brand}`}/>
      <div className="w-method-body">
        <div className="w-method-row1">
          {m.last4 ? `•••• ${m.last4}` : m.name}
          {m.isDefault && <span className="pill">Default</span>}
        </div>
        <div className={`w-method-row2 ${m.expiringSoon ? "expiring" : ""}`}>
          {m.exp ? `${m.expiringSoon ? "⚠ Scade " : "Scade "}${m.exp}` : "Wallet del dispositivo"}
        </div>
      </div>
      <button className="w-method-menu" title="Opzioni"><DotsIcon size={16}/></button>
    </div>
  );
}

function MethodsPanel() {
  return (
    <section className="w-panel">
      <div className="w-panel-head">
        <div className="w-panel-title">
          Metodi di pagamento
          <span className="count">{METHODS_DATA.length}</span>
        </div>
      </div>
      <div className="w-methods-list">
        {METHODS_DATA.map(m => <MethodRow key={m.id} m={m}/>)}
      </div>
      <button className="w-add-method">
        <PlusIcon size={14}/>
        Aggiungi carta o wallet
      </button>
    </section>
  );
}

// ============= DOCS =============
function DocsPanel() {
  return (
    <section className="w-panel">
      <div className="w-panel-head">
        <div className="w-panel-title">Documenti</div>
      </div>
      <div className="w-doc-list">
        {DOCS_DATA.map(d => (
          <div className="w-doc" key={d.id}>
            <div className="w-doc-icon"><FileIcon size={16}/></div>
            <div className="w-doc-body">
              <div className="w-doc-name">{d.name}</div>
              <div className="w-doc-size">{d.size}</div>
            </div>
            <button className="w-doc-dl"><DownloadIcon size={14}/></button>
          </div>
        ))}
      </div>
    </section>
  );
}

// ============= INFO =============
function InfoPanel() {
  return (
    <section className="w-info-panel">
      <div className="ic"><InfoIcon size={18}/></div>
      <div>
        <div className="t">Come funziona il wallet</div>
        <div className="s">
          Il saldo è in € ed è utilizzabile su tutto Sonara. Bonus, refund e ricariche confluiscono in un saldo unico. Quando paghi con il wallet evita le commissioni del circuito carte. <a href="#" onClick={(e) => e.preventDefault()}>Scopri di più</a>
        </div>
      </div>
    </section>
  );
}

// ============= TOPUP MODAL =============
function TopupModal({ open, onClose }) {
  const [preset, setPreset] = React.useState(50);
  const [custom, setCustom] = React.useState("");
  const [methodId, setMethodId] = React.useState("m1");

  React.useEffect(() => {
    if (open) { setPreset(50); setCustom(""); setMethodId("m1"); }
  }, [open]);

  if (!open) return null;

  const amount = custom ? parseFloat(custom) || 0 : preset;
  const canConfirm = amount >= 5 && methodId;

  return (
    <div className="w-modal-backdrop" onClick={onClose}>
      <div className="w-modal" onClick={(e) => e.stopPropagation()}>
        <div className="w-modal-head">
          <div className="t">Ricarica wallet</div>
          <button className="w-modal-close" onClick={onClose}>×</button>
        </div>
        <div className="w-modal-body">
          <div className="w-modal-section">
            <div className="w-modal-label">Importo preset</div>
            <div className="w-preset-grid">
              {[25, 50, 100, 250].map(v => (
                <button key={v} className={`w-preset ${preset === v && !custom ? "active" : ""}`} onClick={() => { setPreset(v); setCustom(""); }}>
                  €{v}
                </button>
              ))}
            </div>
          </div>

          <div className="w-modal-section">
            <div className="w-modal-label">O importo personalizzato</div>
            <input
              className="w-amount-input"
              type="number"
              min="5"
              step="1"
              placeholder="€ 0"
              value={custom}
              onChange={(e) => setCustom(e.target.value)}
            />
          </div>

          <div className="w-modal-section">
            <div className="w-modal-label">Paga con</div>
            <div className="w-method-pick">
              {METHODS_DATA.map(m => (
                <div
                  key={m.id}
                  className={`w-method-pick-row ${methodId === m.id ? "checked" : ""}`}
                  onClick={() => setMethodId(m.id)}
                >
                  <span className="w-radio"/>
                  <div className={`w-card-art ${m.brand}`}/>
                  <div className="w-method-row1" style={{ fontSize: 13 }}>
                    {m.last4 ? `•••• ${m.last4}` : m.name}
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="w-modal-foot">
          <div className="summary">Ricarica totale<br/><strong>€{amount.toFixed(2).replace(".", ",")}</strong></div>
          <button className="w-modal-confirm" disabled={!canConfirm}>
            Conferma
            <ChevronRight size={14}/>
          </button>
        </div>
      </div>
    </div>
  );
}

// ============= PAGE =============
function WalletPage() {
  const [topupOpen, setTopupOpen] = React.useState(false);

  return (
    <main className="page" data-screen-label="Wallet">
      <div className="greet">
        <div>
          <h1 className="hello">Wallet</h1>
          <div className="sub">Saldo, ricariche, transazioni e metodi di pagamento.</div>
        </div>
      </div>

      <WalletHero onTopup={() => setTopupOpen(true)}/>

      <div className="w-grid">
        <div className="w-col">
          <TxPanel/>
          <InfoPanel/>
        </div>
        <div className="w-col">
          <MethodsPanel/>
          <DocsPanel/>
        </div>
      </div>

      <TopupModal open={topupOpen} onClose={() => setTopupOpen(false)}/>
    </main>
  );
}

window.WalletPage = WalletPage;
