// extras.jsx — notifications, ⌘K palette, onboarding, skeletons, print docs, downloads, message thread
const { useState: useX, useEffect: useXE, useRef: useXR } = React;

/* ============================================================
   DOWNLOAD HELPERS
   ============================================================ */
function downloadFile(name, content, type = 'text/plain;charset=utf-8') {
  const blob = new Blob([content], { type });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = name; document.body.appendChild(a); a.click();
  setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 600);
}
function toCSV(headers, rows) {
  const esc = v => `"${String(v ?? '').replace(/"/g, '""')}"`;
  return '\ufeff' + [headers, ...rows].map(r => r.map(esc).join(';')).join('\r\n');
}
function exportLeadsCSV(leads) {
  const headers = ['ID', 'Prénom', 'Nom', 'Départ', 'Arrivée', 'Formule', 'Date soumis', 'Valeur (€)', 'Statut', 'Commission (€)'];
  const rows = leads.map(l => [l.id, l.first, l.last, l.from, l.to,
    l.formule === 'unknown' ? '—' : window.LBC_DATA.FORMULES[l.formule].label,
    l.submitted, l.estValue || '', window.LBC_DATA.STATUS[l.status].label, l.commission || '']);
  downloadFile('lbc-leads-' + Date.now() + '.csv', toCSV(headers, rows), 'text/csv;charset=utf-8');
}
function exportCommissionsCSV(rows) {
  const headers = ['Client', 'Trajet', 'Valeur (€)', 'Taux (%)', 'Commission (€)', 'Statut', 'Date versement'];
  const data = rows.map(({ l, cs, date }) => [`${l.first} ${l.last}`, `${l.from} → ${l.to}`, l.value, l.rate, l.commission, cs.l, date]);
  downloadFile('lbc-commissions-' + Date.now() + '.csv', toCSV(headers, data), 'text/csv;charset=utf-8');
}
Object.assign(window, { exportLeadsCSV, exportCommissionsCSV, downloadFile });

/* ============================================================
   NOTIFICATIONS PANEL
   ============================================================ */
function NotificationsPanel({ notifs, onClose, onReadAll, mobile }) {
  const toneColor = { effectue:'var(--effectue)', verse:'var(--verse)', devis:'var(--devis)', recu:'var(--recu)', accepte:'var(--accepte)' };
  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="pop" style={ mobile
        ? { top:88, left:16, right:16 }
        : { top:58, right:28, width:360 }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'14px 16px', borderBottom:'1px solid var(--border)' }}>
          <span style={{ fontSize:14.5, fontWeight:600, color:'var(--ink)' }}>Notifications</span>
          <button onClick={onReadAll} style={{ fontSize:12.5, color:'var(--brand)', fontWeight:600 }}>Tout marquer lu</button>
        </div>
        <div className="scroll" style={{ maxHeight:380, overflowY:'auto' }}>
          {notifs.map(n => (
            <div key={n.id} className="notif-row" style={{ display:'flex', gap:12, padding:'13px 16px', borderBottom:'1px solid var(--border)', cursor:'pointer', position:'relative' }}>
              <span style={{ width:34, height:34, borderRadius:9, flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center',
                background: (toneColor[n.tone]||'var(--muted)')+'1c', color: toneColor[n.tone]||'var(--muted)' }}><Icon name={n.icon} size={17} /></span>
              <div style={{ minWidth:0, flex:1 }}>
                <div style={{ fontSize:13.5, fontWeight:600, color:'var(--ink)' }}>{n.title}</div>
                <div style={{ fontSize:12.5, color:'var(--muted)', marginTop:2, lineHeight:1.4 }}>{n.body}</div>
                <div style={{ fontSize:11.5, color:'var(--faint)', marginTop:5 }}>{n.time}</div>
              </div>
              {n.unread && <span style={{ width:8, height:8, borderRadius:'50%', background:'var(--brand-bright)', flexShrink:0, marginTop:4 }} />}
            </div>
          ))}
        </div>
        <div style={{ padding:'11px 16px', textAlign:'center' }}>
          <span style={{ fontSize:12.5, color:'var(--muted)' }}>Vous êtes à jour ✦</span>
        </div>
      </div>
    </>
  );
}

/* ============================================================
   COMMAND PALETTE (⌘K)
   ============================================================ */
function CommandPalette({ leads, go, onClose }) {
  const [q, setQ] = useX('');
  const [sel, setSel] = useX(0);
  const inputRef = useXR(null);
  useXE(() => { inputRef.current && inputRef.current.focus(); }, []);

  const pages = [
    { type:'page', label:'Dashboard', icon:'dashboard', go:()=>go('dashboard') },
    { type:'page', label:'Envoyer un nouveau lead', icon:'plus', go:()=>go('new-lead') },
    { type:'page', label:'Mes leads', icon:'list', go:()=>go('leads') },
    { type:'page', label:'Mes commissions', icon:'euro', go:()=>go('commissions') },
    { type:'page', label:'Niveaux partenaires', icon:'award', go:()=>go('tiers') },
    { type:'page', label:'Ressources', icon:'download', go:()=>go('resources') },
    { type:'page', label:'Paramètres', icon:'settings', go:()=>go('settings') },
  ];
  const leadItems = leads.map(l => ({ type:'lead', label:`${l.first} ${l.last}`, sub:`${l.from} → ${l.to}`, icon:'user', status:l.status, go:()=>go('lead-detail',{id:l.id}) }));
  const ql = q.toLowerCase();
  const results = !q ? [...pages.slice(0,4), ...leadItems.slice(0,4)]
    : [...pages, ...leadItems].filter(r => (r.label+' '+(r.sub||'')).toLowerCase().includes(ql)).slice(0,8);

  useXE(()=>{ setSel(0); }, [q]);
  const run = (r) => { r && r.go(); onClose(); };
  const onKey = (e) => {
    if (e.key==='ArrowDown'){ e.preventDefault(); setSel(s=>Math.min(results.length-1,s+1)); }
    else if (e.key==='ArrowUp'){ e.preventDefault(); setSel(s=>Math.max(0,s-1)); }
    else if (e.key==='Enter'){ e.preventDefault(); run(results[sel]); }
    else if (e.key==='Escape'){ onClose(); }
  };

  return (
    <div className="cmdk-overlay" onClick={onClose}>
      <div className="cmdk" onClick={e=>e.stopPropagation()}>
        <div style={{ display:'flex', alignItems:'center', gap:12, padding:'15px 18px', borderBottom:'1px solid var(--border)' }}>
          <span style={{ color:'var(--faint)', display:'flex' }}><Icon name="search" size={19} /></span>
          <input ref={inputRef} value={q} onChange={e=>setQ(e.target.value)} onKeyDown={onKey}
            placeholder="Rechercher un client, une page…" style={{ flex:1, border:'none', outline:'none', fontSize:15, color:'var(--ink)', background:'transparent' }} />
          <span className="kbd">Esc</span>
        </div>
        <div className="scroll" style={{ maxHeight:340, overflowY:'auto', padding:'6px' }}>
          {results.length===0 && <div style={{ padding:'28px', textAlign:'center', color:'var(--muted)', fontSize:13.5 }}>Aucun résultat pour « {q} »</div>}
          {results.map((r,i)=>(
            <div key={i} className={'cmdk-item'+(i===sel?' sel':'')} onMouseEnter={()=>setSel(i)} onClick={()=>run(r)} style={{ borderRadius:9 }}>
              <span style={{ width:32, height:32, borderRadius:8, background:'var(--bg)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ink-2)', flexShrink:0 }}><Icon name={r.icon} size={16} /></span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:13.5, fontWeight:500, color:'var(--ink)' }}>{r.label}</div>
                {r.sub && <div style={{ fontSize:12, color:'var(--muted)' }}>{r.sub}</div>}
              </div>
              {r.type==='lead' ? <StatusBadge status={r.status} /> : <span style={{ fontSize:11.5, color:'var(--faint)' }}>Aller →</span>}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   ONBOARDING TOUR
   ============================================================ */
function OnboardingTour({ onClose, go }) {
  const steps = [
    { emoji:'👋', mascot:true, title:`Bienvenue, ${window.LBC_DATA.PARTNER.firstName} !`, body:"Voici votre espace partenaire LBC. En 30 secondes, voyons comment générer vos premières commissions." },
    { icon:'plus', title:'1 · Envoyez un lead', body:"Un client qui déménage ? Transmettez-le en quelques secondes. Nous le contactons sous 24 h." },
    { icon:'zap', title:'2 · Suivez en temps réel', body:"Chaque lead avance dans un suivi clair — du premier contact jusqu'au déménagement réalisé." },
    { icon:'euroCircle', title:'3 · Encaissez vos commissions', body:"Dès le déménagement effectué, votre commission est versée automatiquement sur votre IBAN." },
  ];
  const [i, setI] = useX(0);
  const s = steps[i];
  const last = i === steps.length - 1;
  return (
    <div className="tour-overlay" onClick={onClose}>
      <div className="tour-card" onClick={e=>e.stopPropagation()}>
        <div style={{ background:'var(--navy)', padding:'34px 30px 28px', textAlign:'center', position:'relative', overflow:'hidden' }}>
          <div style={{ position:'absolute', top:0, left:0, right:0, height:4, background:'linear-gradient(90deg,var(--brand),var(--brand-bright))' }} />
          <div style={{ position:'absolute', top:-30, right:-20, width:160, height:160, borderRadius:'50%', background:'radial-gradient(circle, rgba(224,65,31,.18), transparent 65%)' }} />
          {s.mascot
            ? <Mascot size={96} style={{ margin:'0 auto', boxShadow:'0 12px 30px rgba(0,0,0,.3)' }} />
            : <div style={{ width:72, height:72, borderRadius:20, margin:'0 auto', background:'rgba(224,65,31,.18)', color:'var(--cream)', display:'flex', alignItems:'center', justifyContent:'center' }}><Icon name={s.icon} size={34} /></div>}
        </div>
        <div style={{ padding:'26px 30px 28px', textAlign:'center' }}>
          <h2 style={{ fontSize:20, fontWeight:600, color:'var(--ink)', margin:'0 0 10px' }}>{s.title}</h2>
          <p style={{ fontSize:14, color:'var(--muted)', lineHeight:1.55, margin:'0 auto', maxWidth:320 }}>{s.body}</p>
          <div style={{ display:'flex', justifyContent:'center', gap:7, margin:'22px 0' }}>
            {steps.map((_,j)=><span key={j} style={{ width: j===i?22:7, height:7, borderRadius:999, background: j===i?'var(--brand)':'var(--border-2)', transition:'.2s' }} />)}
          </div>
          <div style={{ display:'flex', gap:10, justifyContent:'center' }}>
            {!last && <button className="btn btn-ghost" onClick={onClose}>Passer</button>}
            <button className="btn btn-primary" onClick={()=>{ if(last){ onClose(); go('new-lead'); } else setI(i+1); }}>
              {last ? 'Envoyer mon premier lead' : 'Suivant'}{!last && <Icon name="arrowR" size={16} />}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   SKELETONS
   ============================================================ */
function SkelCard({ h = 96 }) { return <div className="card" style={{ height:h, padding:18 }}><SkelLine w="50%" h={11} /><SkelLine w="70%" h={22} style={{ marginTop:14 }} /></div>; }
function SkelTable({ rows = 6 }) {
  return (
    <div className="card" style={{ padding:'18px 20px' }}>
      <SkelLine w={160} h={14} />
      <div style={{ marginTop:18, display:'flex', flexDirection:'column', gap:16 }}>
        {Array.from({ length:rows }).map((_,i)=>(
          <div key={i} style={{ display:'flex', alignItems:'center', gap:16 }}>
            <SkelLine w={130} h={12} /><SkelLine w={110} h={12} /><SkelLine w={70} h={12} />
            <div style={{ flex:1 }} /><SkelLine w={80} h={20} r={999} /><SkelLine w={60} h={12} />
          </div>
        ))}
      </div>
    </div>
  );
}
function PageSkeleton({ screen, mobile }) {
  const cols = mobile ? '1fr 1fr' : 'repeat(4,1fr)';
  if (screen==='leads') return <div style={{ display:'flex', flexDirection:'column', gap:18 }}><SkelLine w={260} h={36} r={9} /><SkelTable rows={7} /></div>;
  if (screen==='lead-detail') return (
    <div style={{ display:'grid', gridTemplateColumns: mobile?'1fr':'1fr 1fr', gap:18 }}>
      <SkelCard h={260} /><SkelCard h={260} />
    </div>);
  if (screen==='commissions') return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div style={{ display:'grid', gridTemplateColumns:cols, gap: mobile?12:18 }}>{Array.from({length:4}).map((_,i)=><SkelCard key={i} />)}</div>
      <SkelTable rows={6} />
    </div>);
  // default: dashboard
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:22 }}>
      <div className="card" style={{ height: mobile?120:130 }} />
      <div style={{ display:'grid', gridTemplateColumns:cols, gap: mobile?12:18 }}>{Array.from({length:4}).map((_,i)=><SkelCard key={i} />)}</div>
      <SkelTable rows={5} />
    </div>
  );
}

Object.assign(window, { NotificationsPanel, CommandPalette, OnboardingTour, PageSkeleton });
