// ============================================================
// WASIED · App pages - Dashboard hub + Orders + Billing + Support + Settings + Affiliate + lists
// ============================================================

// ---------- Dashboard hub ----------
function AppDashboardHome() {
  return (
    <AppShell title="Vue d'ensemble" breadcrumbs={[{ label: 'Dashboard' }]}
      actions={<Button variant="primary" size="sm" icon="plus" href="#/quote">Nouvelle commande</Button>}>
      <div style={{ marginBottom: 28 }}>
        <h1 className="h-display" style={{ fontSize: 22, margin: 0, marginBottom: 6, letterSpacing: 'var(--tracking-snug)' }}>
          Bonjour, <span style={{ color: 'var(--accent)' }}>{DATA.client.name}</span>
        </h1>
        <p style={{ fontSize: 13, color: 'var(--fg-3)', margin: 0 }}>Voici l'activité de votre écosystème Wasied aujourd'hui.</p>
      </div>

      {/* KPI tiles */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 32 }} className="dash-kpis">
        <KpiTile color="var(--service-hosting)" icon="server" label="Serveurs actifs" value="2" sub="100 % uptime · 30 j"/>
        <KpiTile color="var(--service-formations)" icon="graduation" label="Formation Expert" value="42 %" sub="36 / 87 modules"/>
        <KpiTile color="var(--service-orders)" icon="briefcase" label="Commandes en cours" value="1" sub="#0418 · en relecture"/>
        <KpiTile color="var(--xp)" icon="euro" label="Prochaine facture" value={`${DATA.client.nextInvoice.amount} €`} sub={DATA.client.nextInvoice.date}/>
      </div>

      {/* Main 2-col layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14 }} className="dash-main">
        {/* Left column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Active servers */}
          <Panel style={{ padding: 22 }}>
            <SectionHead title="Vos serveurs" link={{ label: 'Tout voir', to: '/app/hosting' }}/>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <ServerRow name="maincityrp" plan="Community Pro" status="running" players="47 / 80" cpu="38%" id="srv-1a2b3c"/>
              <ServerRow name="dev-instance" plan="Dev Kit" status="running" players="2 / 5" cpu="12%" id="srv-2b3c4d"/>
            </div>
          </Panel>

          {/* Formations in progress */}
          <Panel style={{ padding: 22 }}>
            <SectionHead title="Formation en cours" link={{ label: 'Reprendre', to: '/app/formations/glua-mastery' }}/>
            <div style={{ padding: 18, background: 'var(--surface-2)', borderRadius: 10 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
                <div style={{ width: 40, height: 40, borderRadius: 10, background: 'rgba(196,181,253,0.12)', color: 'var(--service-formations)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon name="graduation" size={20}/>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)' }}>GLua Mastery · Pack Expert</div>
                  <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>Chapitre 04 · Module 04.03 - SWEP de base</div>
                </div>
                <Badge tone="formations">42 %</Badge>
              </div>
              <div style={{ height: 4, background: 'var(--surface-3)', borderRadius: 2, overflow: 'hidden' }}>
                <div style={{ width: '42%', height: '100%', background: 'var(--service-formations)' }}/>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 14 }}>
                <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>36 / 87 modules · prochaine session 1:1 le 4 juin</span>
                <Button variant="ghost" size="sm" href="#/app/formations/glua-mastery">Continuer</Button>
              </div>
            </div>
          </Panel>

          {/* Active orders */}
          <Panel style={{ padding: 22 }}>
            <SectionHead title="Commandes en cours" link={{ label: 'Tout voir', to: '/app/orders' }}/>
            <Link to="/app/orders/0418">
              <div style={{ padding: 18, background: 'var(--surface-2)', borderRadius: 10, transition: 'background 120ms ease' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-3)'}
                onMouseLeave={e => e.currentTarget.style.background = 'var(--surface-2)'}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
                  <div style={{ width: 40, height: 40, borderRadius: 10, background: 'rgba(110,231,167,0.12)', color: 'var(--service-orders)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon name="briefcase" size={20}/>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)' }}>#0418 · Addon braquage banque v2</div>
                    <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>Budget 4 800 € · livraison prévue le 30 juin</div>
                  </div>
                  <Badge tone="orders" dot>En relecture</Badge>
                </div>
                <div style={{ display: 'flex', gap: 4 }}>
                  {['Devis', 'Acompte', 'Dev', 'Relecture', 'Livré'].map((s, i) => (
                    <div key={i} style={{ flex: 1, height: 4, background: i <= 3 ? 'var(--service-orders)' : 'var(--surface-3)', borderRadius: 2 }}/>
                  ))}
                </div>
              </div>
            </Link>
          </Panel>
        </div>

        {/* Right column - timeline & quick actions */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Panel style={{ padding: 22 }}>
            <SectionHead title="Actions rapides"/>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <QuickAction icon="plus" label="Nouvelle commande" to="/quote" color="var(--service-orders)"/>
              <QuickAction icon="server" label="Acheter hosting" to="/hosting" color="var(--service-hosting)"/>
              <QuickAction icon="graduation" label="Reprendre cours" to="/app/formations/glua-mastery" color="var(--service-formations)"/>
              <QuickAction icon="ticket" label="Ouvrir un ticket" to="/app/support" color="var(--xp)"/>
            </div>
          </Panel>

          <Panel style={{ padding: 22 }}>
            <SectionHead title="Activité récente" link={{ label: 'Tout voir', to: '/app/logs' }}/>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {DATA.client.timeline.map((t, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '12px 0', borderTop: i > 0 ? '1px solid var(--border-1)' : 'none' }}>
                  <div style={{ width: 28, height: 28, borderRadius: 7, background: 'var(--surface-2)', color: 'var(--fg-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={t.icon} size={13}/></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.5 }}>{t.text}</div>
                    <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 2 }}>{t.t}</div>
                  </div>
                </div>
              ))}
            </div>
          </Panel>

          <Panel style={{ padding: 22 }}>
            <SectionHead title="Statut Wasied"/>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 0' }}>
              <span className="live-dot" style={{ width: 8, height: 8, background: 'var(--cash)', color: 'var(--cash)', borderRadius: '50%' }}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--cash)' }}>Tous les systèmes opérationnels</div>
                <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>Dernier check il y a 23 sec.</div>
              </div>
              <Link to="/status" style={{ fontSize: 12, color: 'var(--accent)' }}>Détails →</Link>
            </div>
          </Panel>
        </div>
      </div>

      <style>{`
        @media (max-width: 980px) { .dash-kpis { grid-template-columns: repeat(2, 1fr) !important; } .dash-main { grid-template-columns: 1fr !important; } }
      `}</style>
    </AppShell>
  );
}

function KpiTile({ color, icon, label, value, sub }) {
  return (
    <Panel hoverable style={{ padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
        <div style={{ width: 28, height: 28, borderRadius: 7, background: `color-mix(in srgb, ${color} 14%, var(--surface-2))`, color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={icon} size={14}/></div>
        <span style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500 }}>{label}</span>
      </div>
      <div style={{ fontSize: 26, fontWeight: 600, color: 'var(--fg-1)', letterSpacing: 'var(--tracking-tight)', fontVariantNumeric: 'tabular-nums', marginBottom: 4 }}>{value}</div>
      <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{sub}</div>
    </Panel>
  );
}

function SectionHead({ title, link }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
      <h3 style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)', margin: 0 }}>{title}</h3>
      {link && <Link to={link.to} style={{ fontSize: 12, color: 'var(--accent)' }}>{link.label} →</Link>}
    </div>
  );
}

function ServerRow({ name, plan, status, players, cpu, id }) {
  return (
    <Link to={`/app/hosting/${id}`}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 100px 100px 100px 20px', gap: 14, alignItems: 'center', padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 8, transition: 'background 120ms ease' }}
        onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-3)'}
        onMouseLeave={e => e.currentTarget.style.background = 'var(--surface-2)'}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
          <span className="live-dot" style={{ width: 6, height: 6, background: 'var(--cash)', color: 'var(--cash)', borderRadius: '50%' }}/>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}</div>
            <div style={{ fontSize: 10, color: 'var(--fg-3)', fontFamily: 'var(--font-mono)' }}>{id}</div>
          </div>
        </div>
        <Badge tone="hosting" size="sm">{plan}</Badge>
        <div style={{ fontSize: 12, color: 'var(--fg-2)', fontVariantNumeric: 'tabular-nums' }}>{players}</div>
        <div style={{ fontSize: 12, color: 'var(--fg-2)', fontVariantNumeric: 'tabular-nums' }}>CPU {cpu}</div>
        <Icon name="chevron" size={12} color="var(--fg-3)"/>
      </div>
    </Link>
  );
}

function QuickAction({ icon, label, to, color }) {
  return (
    <Link to={to}>
      <div style={{ padding: 14, background: 'var(--surface-2)', border: '1px solid var(--border-1)', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 10, transition: 'all 120ms ease' }}
        onMouseEnter={e => { e.currentTarget.style.background = 'var(--surface-3)'; e.currentTarget.style.borderColor = 'var(--border-2)'; }}
        onMouseLeave={e => { e.currentTarget.style.background = 'var(--surface-2)'; e.currentTarget.style.borderColor = 'var(--border-1)'; }}>
        <div style={{ width: 24, height: 24, borderRadius: 6, background: `color-mix(in srgb, ${color} 14%, var(--surface-3))`, color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={icon} size={12}/></div>
        <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--fg-1)' }}>{label}</span>
      </div>
    </Link>
  );
}

// ---------- App Hosting list ----------
function AppHostingList() {
  return (
    <AppShell title="Hébergement" breadcrumbs={[{ label: 'Hébergement' }]}
      actions={<Button variant="primary" size="sm" icon="plus" href="#/hosting">Ajouter un serveur</Button>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <ServerRow name="maincityrp" plan="Community Pro" status="running" players="47 / 80" cpu="38%" id="srv-1a2b3c"/>
        <ServerRow name="dev-instance" plan="Dev Kit" status="running" players="2 / 5" cpu="12%" id="srv-2b3c4d"/>
      </div>
    </AppShell>
  );
}

// ---------- App Orders list ----------
function AppOrdersList() {
  return (
    <AppShell title="Commandes" breadcrumbs={[{ label: 'Commandes' }]}
      actions={<Button variant="primary" size="sm" icon="plus" href="#/quote">Nouvelle commande</Button>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          { id: '0418', name: 'Addon braquage banque v2', status: 'En relecture', tone: 'orders', step: 4 },
          { id: '0388', name: 'Refonte HUD principal', status: 'Livré', tone: 'cash', step: 5 },
          { id: '0301', name: 'Bot Discord stats serveur', status: 'Livré', tone: 'cash', step: 5 },
        ].map(o => (
          <Link key={o.id} to={`/app/orders/${o.id}`}>
            <div style={{ display: 'grid', gridTemplateColumns: '100px 1fr 200px 120px', gap: 16, alignItems: 'center', padding: '14px 18px', background: 'var(--surface-1)', border: '1px solid var(--border-1)', borderRadius: 10, transition: 'border-color 120ms ease' }}
              onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--border-2)'}
              onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--border-1)'}>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)' }}>#{o.id}</span>
              <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)' }}>{o.name}</span>
              <div style={{ display: 'flex', gap: 3 }}>
                {['Devis', 'Acompte', 'Dev', 'Relecture', 'Livré'].map((s, i) => (
                  <div key={i} style={{ flex: 1, height: 3, background: i < o.step ? `var(--service-${o.tone === 'orders' ? 'orders' : 'orders'})` : 'var(--surface-3)', borderRadius: 2 }}/>
                ))}
              </div>
              <div style={{ textAlign: 'right' }}><Badge tone={o.tone}>{o.status}</Badge></div>
            </div>
          </Link>
        ))}
      </div>
    </AppShell>
  );
}

// ---------- Order detail ----------
function AppOrderDetail({ id }) {
  const [tab, setTab] = React.useState('thread');
  const [message, setMessage] = React.useState('');
  const messages = [
    { from: 'wasied', t: 'Hier · 18:42', text: "Hello, j'ai posté une version test côté staging. Vous pouvez tester via le serveur dev. J'ai ajouté la mécanique de mini-jeu sur les coffres, deux variantes possibles." },
    { from: 'spacev', t: 'Hier · 19:08', text: "C'est top. Quelques retours après test : (1) le timing du mini-jeu coffre 2 est trop court, (2) il manque l'animation d'ouverture, (3) le son d'alerte police pourrait être plus fort." },
    { from: 'wasied', t: 'Aujourd\'hui · 09:12', text: "OK, je note. Pour le (1) je propose 8 sec au lieu de 5. Pour le (2), j'ai une animation valveBiped sous la main, je l'intègre. Pour le (3), je remonte le volume de +6dB." },
    { from: 'spacev', t: 'Aujourd\'hui · 10:04', text: "Parfait, validé sur les 3 points. À combien de temps tu estimes la suite ?" },
    { from: 'wasied', t: 'Aujourd\'hui · 10:09', text: "Je livre la révision finale demain soir. Solde 70 % à régler ensuite via le lien Stripe sécurisé." },
  ];
  return (
    <AppShell title={`Commande #${id}`} breadcrumbs={[{ label: 'Commandes', path: '/app/orders' }, { label: `#${id}` }]}
      actions={<><Button variant="ghost" size="sm" icon="download">Brief PDF</Button><Button variant="primary" size="sm" icon="check">Valider la révision</Button></>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 14, alignItems: 'flex-start' }} className="dash-main">
        <Panel style={{ padding: 0, overflow: 'hidden' }}>
          {/* Tabs */}
          <div style={{ display: 'flex', borderBottom: '1px solid var(--border-1)', padding: '0 18px' }}>
            {[{ k: 'thread', label: 'Conversation', icon: 'chat' }, { k: 'files', label: 'Livrables', icon: 'folder' }, { k: 'invoices', label: 'Factures', icon: 'receipt' }].map(t => (
              <button key={t.k} onClick={() => setTab(t.k)} style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                padding: '14px 14px', background: 'transparent', border: 'none', cursor: 'pointer',
                color: tab === t.k ? 'var(--fg-1)' : 'var(--fg-3)', fontWeight: 500, fontSize: 13,
                borderBottom: `2px solid ${tab === t.k ? 'var(--accent)' : 'transparent'}`,
                marginBottom: -1,
              }}>
                <Icon name={t.icon} size={14}/>{t.label}
              </button>
            ))}
          </div>
          {/* Content */}
          {tab === 'thread' && (
            <>
              <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14, maxHeight: 480, overflowY: 'auto' }}>
                {messages.map((m, i) => {
                  const isWasied = m.from === 'wasied';
                  return (
                    <div key={i} style={{ display: 'flex', flexDirection: isWasied ? 'row-reverse' : 'row', gap: 10, alignItems: 'flex-start' }}>
                      <Avatar name={isWasied ? 'Wasied' : 'Spacev'} size={28} tone={isWasied ? 'amber' : 'cyan'}/>
                      <div style={{ maxWidth: '70%', display: 'flex', flexDirection: 'column', alignItems: isWasied ? 'flex-end' : 'flex-start' }}>
                        <div style={{ padding: '10px 14px', background: isWasied ? 'var(--accent-soft)' : 'var(--surface-2)', border: `1px solid ${isWasied ? 'rgba(143,168,255,0.2)' : 'var(--border-1)'}`, borderRadius: 12, fontSize: 13, color: 'var(--fg-1)', lineHeight: 1.55 }}>{m.text}</div>
                        <div style={{ fontSize: 10, color: 'var(--fg-3)', marginTop: 4 }}>{isWasied ? 'Wasied' : 'Vous'} · {m.t}</div>
                      </div>
                    </div>
                  );
                })}
              </div>
              <div style={{ padding: 16, borderTop: '1px solid var(--border-1)', display: 'flex', gap: 10, alignItems: 'flex-end' }}>
                <Textarea placeholder="Votre message…" value={message} onChange={e => setMessage(e.target.value)} style={{ minHeight: 56, maxHeight: 120 }}/>
                <Button variant="primary" size="md" icon="send">Envoyer</Button>
              </div>
            </>
          )}
          {tab === 'files' && (
            <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { name: 'brief-v2.pdf', size: '218 KB', t: 'il y a 4 sem.' },
                { name: 'addon-braquage-v0.9.zip', size: '4.2 MB', t: 'il y a 5 j' },
                { name: 'addon-braquage-v0.95.zip', size: '4.4 MB', t: 'hier' },
                { name: 'screenshots-finaux.zip', size: '12 MB', t: 'aujourd\'hui' },
              ].map((f, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 8 }}>
                  <Icon name="fileText" size={16} color="var(--fg-2)"/>
                  <span style={{ flex: 1, fontSize: 13, fontFamily: 'var(--font-mono)', color: 'var(--fg-1)' }}>{f.name}</span>
                  <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>{f.size}</span>
                  <span style={{ fontSize: 11, color: 'var(--fg-3)', minWidth: 80, textAlign: 'right' }}>{f.t}</span>
                  <Button variant="ghost" size="xs" icon="download">DL</Button>
                </div>
              ))}
            </div>
          )}
          {tab === 'invoices' && (
            <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 8 }}>
              <InvoiceRow id="INV-2026-004-O" label="Acompte 30 %" amount="1 440 €" status="paid" date="2026-04-22"/>
              <InvoiceRow id="INV-2026-006-O" label="Solde 70 %" amount="3 360 €" status="pending" date="à venir"/>
            </div>
          )}
        </Panel>

        {/* Sidebar */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Panel style={{ padding: 22 }}>
            <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, marginBottom: 14 }}>RÉCAPITULATIF</div>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-1)', marginBottom: 10 }}>Addon braquage banque v2</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 13 }}>
              <SidebarStat label="Type" value="Addon GMod"/>
              <SidebarStat label="Budget" value="4 800 €"/>
              <SidebarStat label="Acompte" value="1 440 € · payé"/>
              <SidebarStat label="Solde" value="3 360 € · à payer"/>
              <SidebarStat label="Lancement" value="22 avril 2026"/>
              <SidebarStat label="Livraison" value="30 juin 2026"/>
              <SidebarStat label="Révisions" value="2 / 3"/>
            </div>
          </Panel>
          <Panel style={{ padding: 22 }}>
            <div style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500, marginBottom: 14 }}>WORKFLOW</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {[
                { s: 'Devis envoyé', d: '14 avr.', done: true },
                { s: 'Acompte versé', d: '16 avr.', done: true },
                { s: 'En développement', d: 'depuis 22 avr.', done: true },
                { s: 'En relecture', d: 'depuis hier', done: true, current: true },
                { s: 'Livré · solde', d: 'à venir', done: false },
              ].map((s, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0' }}>
                  <div style={{ width: 18, height: 18, borderRadius: '50%', background: s.done ? 'var(--service-orders)' : 'var(--surface-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    {s.done && <Icon name="check" size={10} color="var(--fg-inv)"/>}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 12, color: s.current ? 'var(--service-orders)' : 'var(--fg-1)', fontWeight: s.current ? 500 : 400 }}>{s.s}</div>
                    <div style={{ fontSize: 10, color: 'var(--fg-3)' }}>{s.d}</div>
                  </div>
                </div>
              ))}
            </div>
          </Panel>
        </div>
      </div>
    </AppShell>
  );
}

function InvoiceRow({ id, label, amount, status, date, service }) {
  const tones = { paid: 'cash', pending: 'xp', overdue: 'hp' };
  const labels = { paid: 'Payée', pending: 'À venir', overdue: 'En retard' };
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr 120px 100px 80px 80px', gap: 16, alignItems: 'center', padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 8 }}>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)' }}>{id}</span>
      <span style={{ fontSize: 13, color: 'var(--fg-1)' }}>{label || service}</span>
      <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>{date}</span>
      <span style={{ fontSize: 13, color: 'var(--fg-1)', textAlign: 'right', fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>{amount}</span>
      <Badge tone={tones[status]} size="sm">{labels[status]}</Badge>
      <Button variant="ghost" size="xs" icon="download">PDF</Button>
    </div>
  );
}

// ---------- App Formations list ----------
function AppFormationsList() {
  return (
    <AppShell title="Formations" breadcrumbs={[{ label: 'Formations' }]}>
      <Panel style={{ padding: 28, background: 'linear-gradient(135deg, var(--surface-1) 0%, rgba(196,181,253,0.04) 100%)', border: '1px solid rgba(196,181,253,0.16)' }}>
        <Badge tone="formations">Pack Expert</Badge>
        <h2 className="h-display" style={{ fontSize: 26, margin: '14px 0 6px' }}>GLua Mastery</h2>
        <p style={{ fontSize: 13, color: 'var(--fg-3)', margin: 0, marginBottom: 22 }}>Acheté le 4 février 2026 · accès illimité · suivi 1:1 jusqu'au 4 mai</p>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
          <div style={{ flex: 1, height: 6, background: 'var(--surface-3)', borderRadius: 3, overflow: 'hidden' }}>
            <div style={{ width: '42%', height: '100%', background: 'var(--service-formations)' }}/>
          </div>
          <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--service-formations)', minWidth: 100, textAlign: 'right' }}>42 % · 36 / 87</span>
        </div>
        <Button variant="primary" size="lg" href="#/app/formations/glua-mastery">Reprendre le cours</Button>
      </Panel>

      <div style={{ marginTop: 28 }}>
        <SectionHead title="Réservation 1:1 avec Maxime"/>
        <Panel style={{ padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
            <Avatar name="Maxime Wasied" size={48} tone="amber"/>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--fg-1)' }}>Prochain créneau · jeudi 4 juin à 18:00</div>
              <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Visio Discord · 45 min · Pack Expert</div>
            </div>
            <Button variant="ghost" icon="calendar">Replanifier</Button>
            <Button variant="primary" icon="play">Rejoindre</Button>
          </div>
        </Panel>
      </div>
    </AppShell>
  );
}

// ---------- Billing ----------
function AppBillingPage() {
  return (
    <AppShell title="Facturation" breadcrumbs={[{ label: 'Facturation' }]}
      actions={<Button variant="ghost" size="sm" icon="download">Tout télécharger</Button>}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 28 }} className="dash-kpis">
        <KpiTile color="var(--accent)" icon="euro" label="Total dépensé · 2026" value="394 €" sub="5 transactions"/>
        <KpiTile color="var(--service-orders)" icon="briefcase" label="Mensuel récurrent" value="34,99 €" sub="Hosting Community Pro"/>
        <KpiTile color="var(--xp)" icon="clock" label="Prochaine facture" value={`${DATA.client.nextInvoice.amount} €`} sub={DATA.client.nextInvoice.date}/>
      </div>

      <Panel style={{ padding: 22, marginBottom: 14 }}>
        <SectionHead title="Abonnements actifs"/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <SubscriptionRow icon="server" color="var(--service-hosting)" name="Hosting Community Pro" sub="maincityrp · renouvelé le 12 du mois" amount="34,99 €/mois"/>
          <SubscriptionRow icon="server" color="var(--service-hosting)" name="Hosting Dev Kit" sub="dev-instance · renouvelé le 18 du mois" amount="7,99 €/mois"/>
        </div>
      </Panel>

      <Panel style={{ padding: 22, marginBottom: 14 }}>
        <SectionHead title="Mode de paiement"/>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 14, background: 'var(--surface-2)', borderRadius: 8 }}>
          <div style={{ width: 40, height: 28, background: 'var(--surface-3)', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--fg-3)' }}><Icon name="credit" size={14}/></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)' }}>Visa •••• 4242</div>
            <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>Expire 12 / 28 · par défaut</div>
          </div>
          <Button variant="ghost" size="sm">Changer</Button>
        </div>
      </Panel>

      <Panel style={{ padding: 22 }}>
        <SectionHead title="Historique des factures"/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {DATA.client.invoices.map(i => <InvoiceRow key={i.id} {...i}/>)}
        </div>
      </Panel>
    </AppShell>
  );
}

function SubscriptionRow({ icon, color, name, sub, amount }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: 'var(--surface-2)', borderRadius: 8 }}>
      <div style={{ width: 32, height: 32, borderRadius: 8, background: `color-mix(in srgb, ${color} 14%, var(--surface-3))`, color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={icon} size={14}/></div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)' }}>{name}</div>
        <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{sub}</div>
      </div>
      <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)', fontVariantNumeric: 'tabular-nums' }}>{amount}</div>
      <Button variant="ghost" size="xs">Annuler</Button>
    </div>
  );
}

// ---------- Support ----------
function AppSupportList() {
  const [filter, setFilter] = React.useState('all');
  const t = DATA.support.tickets;
  return (
    <AppShell title="Support" breadcrumbs={[{ label: 'Support' }]}
      actions={<Button variant="primary" size="sm" icon="plus">Nouveau ticket</Button>}>
      <div style={{ display: 'flex', gap: 6, marginBottom: 18 }}>
        {[
          { v: 'all', label: 'Tous' },
          { v: 'open', label: 'Ouverts' },
          { v: 'awaiting-client', label: 'En attente de vous' },
          { v: 'resolved', label: 'Résolus' },
        ].map(f => (
          <button key={f.v} onClick={() => setFilter(f.v)} style={chipStyle(filter === f.v)}>{f.label}</button>
        ))}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {t.filter(x => filter === 'all' || x.status === filter).map(ticket => (
          <Link key={ticket.id} to={`/app/support/${ticket.id}`}>
            <div style={{ display: 'grid', gridTemplateColumns: '90px 1fr 140px 120px 100px', gap: 14, alignItems: 'center', padding: '14px 18px', background: 'var(--surface-1)', border: '1px solid var(--border-1)', borderRadius: 10 }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)' }}>{ticket.id}</span>
              <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)' }}>{ticket.subject}</span>
              <Badge tone="subtle" size="sm">{ticket.service}</Badge>
              <Badge tone={ticket.priority === 'high' ? 'hp' : 'subtle'} size="sm">{ticket.priority === 'high' ? 'Prioritaire' : 'Normal'}</Badge>
              <span style={{ fontSize: 11, color: 'var(--fg-3)', textAlign: 'right' }}>{ticket.updated}</span>
            </div>
          </Link>
        ))}
      </div>
    </AppShell>
  );
}

function AppSupportThread({ id }) {
  const t = DATA.support.tickets.find(x => x.id === id);
  if (!t) return <NotFound/>;
  return (
    <AppShell title={t.subject} breadcrumbs={[{ label: 'Support', path: '/app/support' }, { label: id }]}>
      <Panel style={{ padding: 22 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 22 }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-3)' }}>{t.id}</span>
          <Badge tone="subtle">{t.service}</Badge>
          <Badge tone={t.priority === 'high' ? 'hp' : 'subtle'}>{t.priority === 'high' ? 'Prioritaire' : 'Normal'}</Badge>
          <Badge tone="cash" dot>Ouvert</Badge>
        </div>
        <h2 className="h-display" style={{ fontSize: 22, margin: 0, marginBottom: 22 }}>{t.subject}</h2>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 18 }}>
          <ThreadMessage from="client" t="il y a 14 min" text="Bonjour, j'ai un pic de lag tous les soirs vers 21:00 qui dure 1-2 minutes. Sur la métrique CPU je vois un spike à 78%. Y a-t-il un moyen de remonter aux hooks qui posent problème ?"/>
          <ThreadMessage from="wasied" t="il y a 8 min" text="Salut, j'ai regardé. Le spike vient du hook PlayerSay surchargé par un addon tiers (anti-spam mal codé). Je peux soit le patcher pour vous, soit vous fournir le diff à appliquer. Vous préférez ?"/>
        </div>
        <Textarea placeholder="Votre réponse…" style={{ minHeight: 100 }}/>
        <div style={{ marginTop: 12, display: 'flex', gap: 8, alignItems: 'center' }}>
          <Button variant="ghost" size="sm" icon="paperclip">Joindre</Button>
          <span style={{ flex: 1 }}/>
          <Button variant="ghost" size="sm">Marquer résolu</Button>
          <Button variant="primary" size="sm" icon="send">Envoyer</Button>
        </div>
      </Panel>
    </AppShell>
  );
}

function ThreadMessage({ from, t, text }) {
  const wasied = from === 'wasied';
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
      <Avatar name={wasied ? 'Wasied' : 'Spacev'} size={32} tone={wasied ? 'amber' : 'cyan'}/>
      <div style={{ flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
          <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)' }}>{wasied ? 'Wasied' : 'Vous'}</span>
          {wasied && <Badge tone="brand" size="sm">Staff</Badge>}
          <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>{t}</span>
        </div>
        <div style={{ fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.6 }}>{text}</div>
      </div>
    </div>
  );
}

// ---------- Settings ----------
function AppSettingsPage() {
  return (
    <AppShell title="Paramètres" breadcrumbs={[{ label: 'Paramètres' }]}>
      <div style={{ maxWidth: 720 }}>
        <Panel style={{ padding: 22, marginBottom: 14 }}>
          <SectionHead title="Profil"/>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
            <Avatar name={DATA.client.name} size={56} tone={DATA.client.avatarTone}/>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--fg-1)' }}>{DATA.client.name}</div>
              <div style={{ fontSize: 12, color: 'var(--fg-3)' }}>Synchronisé via Discord OAuth · @{DATA.client.discord}</div>
            </div>
            <Button variant="ghost" icon="discord" style={{ marginLeft: 'auto' }}>Re-sync</Button>
          </div>
          <Input label="Nom affiché" defaultValue={DATA.client.name}/>
          <div style={{ marginTop: 14 }}>
            <Input label="Email de contact" defaultValue="spacev@exemple.com" type="email" icon="mail"/>
          </div>
        </Panel>

        <Panel style={{ padding: 22, marginBottom: 14 }}>
          <SectionHead title="Notifications"/>
          <Toggle on={true} onChange={()=>{}} label="Notifications email" sub="Factures, livraisons, messages support."/>
          <Toggle on={true} onChange={()=>{}} label="Notifications in-app" sub="Cloche dans la topbar."/>
          <Toggle on={false} onChange={()=>{}} label="Notifications push browser" sub="Idéal pour les events serveur en direct."/>
          <Toggle on={false} onChange={()=>{}} label="Discord Rich Presence" sub="Afficher 'regarde la formation X de Wasied' sur votre profil Discord."/>
        </Panel>

        <Panel style={{ padding: 22, marginBottom: 14 }}>
          <SectionHead title="Webhooks sortants"/>
          <p style={{ fontSize: 12, color: 'var(--fg-3)', margin: 0, marginBottom: 14 }}>Configurez une URL pour recevoir les events de votre compte. Idéal pour intégrer Wasied dans votre stack interne.</p>
          <Input placeholder="https://votre-endpoint.com/wasied-hook" icon="webhook"/>
          <div style={{ display: 'flex', gap: 6, marginTop: 14, flexWrap: 'wrap' }}>
            {['server.restarted', 'order.delivered', 'invoice.paid', 'formations.module.completed'].map(e => <Badge key={e} tone="subtle" size="md">{e}</Badge>)}
          </div>
          <Button variant="primary" size="sm" style={{ marginTop: 14 }}>Sauver le webhook</Button>
        </Panel>

        <Panel style={{ padding: 22 }}>
          <SectionHead title="Zone dangereuse"/>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 14, background: 'rgba(251,113,133,0.04)', border: '1px solid rgba(251,113,133,0.16)', borderRadius: 8 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)' }}>Supprimer mon compte</div>
              <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>Action irréversible · vos serveurs seront résiliés et vos données effacées sous 30 jours.</div>
            </div>
            <Button variant="danger" size="sm">Supprimer</Button>
          </div>
        </Panel>
      </div>
    </AppShell>
  );
}

// ---------- Affiliate ----------
function AppAffiliatePage() {
  return (
    <AppShell title="Affiliation" breadcrumbs={[{ label: 'Affiliation' }]}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 28 }} className="dash-kpis">
        <KpiTile color="var(--accent)" icon="users" label="Filleuls actifs" value="4" sub="depuis 6 mois"/>
        <KpiTile color="var(--service-orders)" icon="euro" label="Commissions cumulées" value="148,72 €" sub="20 % par paiement"/>
        <KpiTile color="var(--xp)" icon="clock" label="En attente" value="32,00 €" sub="versement le 15"/>
        <KpiTile color="var(--cash)" icon="trending" label="Conversion" value="38 %" sub="visites → clients"/>
      </div>

      <Panel style={{ padding: 22, marginBottom: 14 }}>
        <SectionHead title="Votre lien de parrainage"/>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', padding: 14, background: 'var(--surface-2)', border: '1px solid var(--border-1)', borderRadius: 8 }}>
          <code style={{ flex: 1, fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--fg-1)' }}>wasied.com?ref=spacev</code>
          <Button variant="ghost" size="sm" icon="copy">Copier</Button>
        </div>
        <p style={{ fontSize: 12, color: 'var(--fg-3)', margin: 0, marginTop: 12 }}>Vos filleuls bénéficient de 10 % de réduction sur leur premier achat. Vous touchez 20 % de commission à vie sur tous leurs paiements.</p>
      </Panel>

      <Panel style={{ padding: 22 }}>
        <SectionHead title="Historique"/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            { d: 'il y a 3 j', user: 'kogui', event: 'Premier paiement', amount: '+ 7,00 €' },
            { d: 'il y a 1 sem.', user: 'mathieuRP', event: 'Inscription', amount: '-' },
            { d: 'il y a 2 sem.', user: 'damie2pain', event: 'Renouvellement', amount: '+ 7,00 €' },
            { d: 'il y a 1 mois', user: 'wolfcoco', event: 'Premier paiement', amount: '+ 18,00 €' },
          ].map((h, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '90px 1fr 1fr 100px', gap: 16, alignItems: 'center', padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 8 }}>
              <span style={{ fontSize: 12, color: 'var(--fg-3)' }}>{h.d}</span>
              <span style={{ fontSize: 13, color: 'var(--fg-1)' }}>{h.user}</span>
              <span style={{ fontSize: 13, color: 'var(--fg-2)' }}>{h.event}</span>
              <span style={{ fontSize: 13, color: h.amount.includes('+') ? 'var(--cash)' : 'var(--fg-3)', textAlign: 'right', fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>{h.amount}</span>
            </div>
          ))}
        </div>
      </Panel>
    </AppShell>
  );
}

// ---------- App Addons list ----------
function AppAddonsList() {
  return (
    <AppShell title="Addons" breadcrumbs={[{ label: 'Addons' }]}
      actions={<Button variant="primary" size="sm" icon="search" href="#/addons">Parcourir le catalogue</Button>}>
      <div style={{ marginBottom: 24 }}>
        <Panel style={{ padding: 22 }}>
          <SectionHead title="Mes addons premium achetés"/>
          <div style={{ padding: '20px 14px', textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
            Vous n'avez pas encore acheté d'addons premium. Parcourez le <Link to="/addons" style={{ color: 'var(--accent)' }}>catalogue</Link> pour découvrir Banking Pro et Factions Pro.
          </div>
        </Panel>
      </div>
      <Panel style={{ padding: 22 }}>
        <SectionHead title="Téléchargements (gratuits)"/>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {DATA.addons.list.filter(a => a.price === 0).slice(0, 4).map(a => (
            <div key={a.id} style={{ display: 'grid', gridTemplateColumns: '40px 1fr 100px 100px', gap: 14, alignItems: 'center', padding: '10px 14px', background: 'var(--surface-2)', borderRadius: 8 }}>
              <div style={{ width: 32, height: 32, borderRadius: 8, background: 'rgba(251,191,36,0.10)', color: 'var(--service-addons)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="package" size={14}/></div>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--fg-1)' }}>{a.name}</div>
                <div style={{ fontSize: 11, color: 'var(--fg-3)' }}>v2.4.0 · MAJ {a.updated}</div>
              </div>
              <Badge tone="cash" size="sm">Gratuit</Badge>
              <Button variant="ghost" size="xs" icon="download">DL</Button>
            </div>
          ))}
        </div>
      </Panel>
    </AppShell>
  );
}

Object.assign(window, {
  AppDashboardHome, AppHostingList, AppOrdersList, AppOrderDetail, AppFormationsList,
  AppBillingPage, AppSupportList, AppSupportThread, AppSettingsPage, AppAffiliatePage,
  AppAddonsList, KpiTile, SectionHead, InvoiceRow, ThreadMessage,
});
