// gestion-extra.jsx — planning calendrier, messagerie partagée, timeline activité, login staff
const { useState: useG, useRef: useGR, useEffect: useGE } = React;

/* ============== STAFF LOGIN (Admin / Back-office) ============== */
const STAFF_PROFILES = {
  admin:   { title:'Espace interne LBC', sub:'Réseau · Clients · Stockage · Finances', badge:'ESPACE LBC', accent:'#E0411F', email:'theo.lambert@lbc.fr' },
  gestion: { title:'Espace interne LBC', sub:'Réseau · Clients · Stockage · Finances', badge:'ESPACE LBC', accent:'#E0411F', email:'theo.lambert@lbc.fr' },
  backoffice:{ title:'Back-office partenaires', sub:'Réseau · Leads · Versements', badge:'BACK-OFFICE', accent:'#E0411F', email:'theo.lambert@lbc.fr' },
};
function StaffLogin({ kind, onLogin }) {
  const p = STAFF_PROFILES[kind] || STAFF_PROFILES.admin;
  const [email, setEmail] = useG(p.email);
  const [pw, setPw] = useG('••••••••');
  return (
    <div style={{ height:'100%', display:'flex', alignItems:'center', justifyContent:'center', background:'radial-gradient(120% 120% at 50% 0%, #16384C 0%, #0B1F2B 70%)', padding:24 }}>
      <div style={{ width:'100%', maxWidth:380, background:'var(--card)', borderRadius:20, overflow:'hidden', boxShadow:'var(--shadow-pop)' }}>
        <div style={{ background:'var(--navy-deep)', padding:'26px 28px', position:'relative', overflow:'hidden' }}>
          <div style={{ position:'absolute', top:0, left:0, right:0, height:4, background:`linear-gradient(90deg, ${p.accent}, var(--brand-bright))` }} />
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <Logo size={22} showSub={false} />
            <span style={{ fontSize:9.5, fontWeight:700, letterSpacing:'.12em', color:p.accent, border:`1px solid ${p.accent}88`, borderRadius:5, padding:'3px 7px' }}>{p.badge}</span>
          </div>
          <h2 style={{ color:'var(--cream)', fontSize:18, fontWeight:600, margin:'18px 0 2px' }}>{p.title}</h2>
          <p style={{ color:'rgba(245,239,227,.6)', fontSize:12.5, margin:0 }}>{p.sub}</p>
        </div>
        <div style={{ padding:'24px 28px 28px', display:'flex', flexDirection:'column', gap:14 }}>
          <div className="field"><label className="label">Email professionnel</label>
            <div className="input-wrap"><span className="lead-icon"><Icon name="mail" size={17} /></span>
              <input className="input has-icon" value={email} onChange={e=>setEmail(e.target.value)} /></div></div>
          <div className="field"><label className="label">Mot de passe</label>
            <div className="input-wrap"><span className="lead-icon"><Icon name="lock" size={17} /></span>
              <input className="input has-icon" type="password" value={pw} onChange={e=>setPw(e.target.value)} /></div></div>
          <button className="btn btn-primary btn-lg btn-block" style={{ marginTop:4 }} onClick={onLogin}>
            <Icon name="lock" size={16} />Accéder à l'espace</button>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'center', gap:7, fontSize:11.5, color:'var(--faint)' }}>
            <Icon name="shield" size={13} />Accès réservé au personnel LBC</div>
        </div>
      </div>
    </div>
  );
}

/* ============== MESSAGERIE PARTAGÉE ============== */
function ChatPanel({ as, chatApi, showToast, title, subtitle, avatar, height = 300 }) {
  const [draft, setDraft] = useG('');
  const endRef = useGR(null);
  const msgs = chatApi.msgs;
  useGE(()=>{ if(endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; }, [msgs.length]);
  const mine = as; // 'client' | 'staff'
  const send = ()=>{ const t=draft.trim(); if(!t) return; chatApi.send(mine, t); setDraft('');
    showToast && showToast(mine==='client'?'Message envoyé à votre conseiller':'Message envoyé au client'); };
  return (
    <div className="card" style={{ display:'flex', flexDirection:'column', overflow:'hidden' }}>
      <div style={{ display:'flex', alignItems:'center', gap:11, padding:'14px 18px', borderBottom:'1px solid var(--border)' }}>
        {avatar==='mascot'
          ? <img src="assets/mascot.png" alt="" width={38} height={38} style={{ borderRadius:'50%' }} />
          : <Avatar initials={avatar||'EM'} size={38} color="var(--navy)" />}
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:14.5, fontWeight:600, color:'var(--ink)' }}>{title}</div>
          <div style={{ fontSize:12, color:'var(--effectue)', display:'flex', alignItems:'center', gap:5 }}><span style={{ width:6, height:6, borderRadius:'50%', background:'var(--effectue)' }} />{subtitle||'En ligne'}</div>
        </div>
      </div>
      <div ref={endRef} className="scroll" style={{ flex:1, display:'flex', flexDirection:'column', gap:10, padding:'16px 18px', overflowY:'auto', minHeight:height, maxHeight:height }}>
        {msgs.map((m,i)=>{
          const isMine = m.from===mine;
          return (
            <div key={i} style={{ display:'flex', flexDirection:'column', alignItems: isMine?'flex-end':'flex-start', gap:3 }}>
              <div className={'msg '+(isMine?'msg-me':'msg-them')}>{m.text}</div>
              <span style={{ fontSize:10.5, color:'var(--faint)', padding:'0 4px' }}>{m.from==='staff'?'Karim · LBC':'Élise'} · {m.time}</span>
            </div>
          );
        })}
      </div>
      <div style={{ display:'flex', gap:9, padding:'12px 16px', borderTop:'1px solid var(--border)' }}>
        <input className="input" value={draft} onChange={e=>setDraft(e.target.value)} onKeyDown={e=>{ if(e.key==='Enter') send(); }} placeholder="Écrire un message…" style={{ flex:1, height:42 }} />
        <button className="btn btn-primary" style={{ width:46, padding:0 }} onClick={send}><Icon name="arrowR" size={18} /></button>
      </div>
    </div>
  );
}

/* ============== MESSAGES — vue Admin (liste + thread) ============== */
function AdminMessages({ chatApi, showToast, mobile }) {
  const convos = [
    { id:'C-2420', name:'Élise Moreau', route:'Nice → Bordeaux', active:true },
    { id:'C-3120', name:'Olivier Meyer', route:'Monaco → Paris', last:'Merci beaucoup !', active:false },
    { id:'C-3108', name:'Laura Bianchi', route:'Nice → Milan', last:'Parfait, à lundi.', active:false },
  ];
  const [sel, setSel] = useG('C-2420');
  const cur = convos.find(c=>c.id===sel);
  const last = chatApi.msgs[chatApi.msgs.length-1];
  const list = (
    <div className="card" style={{ overflow:'hidden' }}>
      <div style={{ padding:'14px 18px', borderBottom:'1px solid var(--border)' }}><span className="section-title" style={{ fontSize:15 }}>Conversations</span></div>
      {convos.map(c=>(
        <div key={c.id} onClick={()=>setSel(c.id)} style={{ display:'flex', alignItems:'center', gap:11, padding:'13px 16px', borderBottom:'1px solid var(--border)', cursor:'pointer', background: sel===c.id?'var(--hover)':'transparent' }}>
          <Avatar initials={c.name.split(' ').map(x=>x[0]).join('')} size={36} color="var(--navy)" />
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:13.5, fontWeight:600, color:'var(--ink)' }}>{c.name}</div>
            <div style={{ fontSize:12, color:'var(--muted)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{c.id===sel ? (last?last.text:c.route) : (c.last||c.route)}</div>
          </div>
          {c.active && <span style={{ width:8, height:8, borderRadius:'50%', background:'var(--brand-bright)', flexShrink:0 }} />}
        </div>
      ))}
    </div>
  );
  const thread = <ChatPanel as="staff" chatApi={chatApi} showToast={showToast} title={cur?cur.name:'Client'} subtitle={cur?cur.route:''} avatar={cur?cur.name.split(' ').map(x=>x[0]).join(''):'C'} height={mobile?340:420} />;
  if (mobile) return <div style={{ display:'flex', flexDirection:'column', gap:16 }}>{list}{thread}</div>;
  return <div style={{ display:'grid', gridTemplateColumns:'320px 1fr', gap:18, alignItems:'start' }}>{list}{thread}</div>;
}

/* ============== PLANNING CALENDRIER ============== */
const PL_TYPE = {
  move:        { label:'Déménagement', color:'var(--brand)',    bg:'rgba(182,61,36,.1)', icon:'truck' },
  retrieval:   { label:'Récupération box', color:'var(--blue)', bg:'rgba(37,99,235,.1)', icon:'package' },
  'storage-in':{ label:'Entrée stockage', color:'var(--accepte)', bg:'rgba(199,122,10,.12)', icon:'package' },
};
const DOW = ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim'];
function PlanningCalendar({ go, mobile, showToast }) {
  const A = window.LBC_ADMIN;
  const { year, month, label } = A.PLANNING_MONTH;
  const events = A.PLANNING;
  const first = new Date(year, month, 1);
  const startDow = (first.getDay()+6)%7; // lundi=0
  const days = new Date(year, month+1, 0).getDate();
  const today = 1; // 1 juin 2026
  const [sel, setSel] = useG(18);
  const evByDay = (d)=> events.filter(e=>e.d===d);
  const cells = [];
  for (let i=0;i<startDow;i++) cells.push(null);
  for (let d=1;d<=days;d++) cells.push(d);
  const selEvents = evByDay(sel);

  const grid = (
    <div className="card card-pad">
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:16 }}>
        <span className="section-title" style={{ fontSize:16 }}>{label}</span>
        <div style={{ display:'flex', gap:6 }}>
          <button className="btn btn-ghost btn-sm" style={{ width:34, opacity:.5 }} disabled><Icon name="chevronL" size={15} /></button>
          <button className="btn btn-ghost btn-sm" style={{ width:34, opacity:.5 }} disabled><Icon name="chevronR" size={15} /></button>
        </div>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:5 }}>
        {DOW.map(d=><div key={d} style={{ fontSize:10.5, fontWeight:600, textTransform:'uppercase', letterSpacing:'.04em', color:'var(--faint)', textAlign:'center', padding:'2px 0 6px' }}>{mobile?d[0]:d}</div>)}
        {cells.map((d,i)=>{
          if (d===null) return <div key={'e'+i} />;
          const evs = evByDay(d);
          const isSel = d===sel, isToday = d===today;
          return (
            <button key={d} onClick={()=>setSel(d)} style={{ position:'relative', aspectRatio:'1', borderRadius:9, padding:'5px 0 0', display:'flex', flexDirection:'column', alignItems:'center', gap:3,
              background: isSel?'var(--navy)':(isToday?'var(--cream)':'var(--bg)'), color: isSel?'var(--cream)':'var(--ink)', transition:'.12s', border: isToday&&!isSel?'1px solid var(--brand)':'1px solid transparent' }}>
              <span className="tnum" style={{ fontSize:13, fontWeight: (isSel||isToday)?700:500 }}>{d}</span>
              <div style={{ display:'flex', gap:2, flexWrap:'wrap', justifyContent:'center', maxWidth:'80%' }}>
                {evs.slice(0,3).map((e,j)=><span key={j} style={{ width:5, height:5, borderRadius:'50%', background: isSel?'var(--cream)':PL_TYPE[e.type].color }} />)}
              </div>
            </button>
          );
        })}
      </div>
      <div style={{ display:'flex', gap:16, flexWrap:'wrap', marginTop:14, paddingTop:14, borderTop:'1px solid var(--border)' }}>
        {Object.keys(PL_TYPE).map(k=>(
          <span key={k} style={{ display:'inline-flex', alignItems:'center', gap:6, fontSize:11.5, color:'var(--muted)' }}>
            <span style={{ width:9, height:9, borderRadius:'50%', background:PL_TYPE[k].color }} />{PL_TYPE[k].label}</span>
        ))}
      </div>
    </div>
  );
  const dayPanel = (
    <div className="card card-pad">
      <div style={{ fontSize:15, fontWeight:600, color:'var(--ink)' }}>{sel} {label.split(' ')[0].toLowerCase()}</div>
      <div style={{ fontSize:12.5, color:'var(--muted)', marginBottom:14 }}>{selEvents.length} évènement{selEvents.length>1?'s':''}</div>
      {selEvents.length===0
        ? <div style={{ padding:'24px 0', textAlign:'center', color:'var(--faint)', fontSize:13 }}>Aucun déménagement ce jour.</div>
        : <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {selEvents.map((e,i)=>{
              const t = PL_TYPE[e.type];
              const cid = (A.ADMIN_CLIENTS.find(c=>c.name===e.client)||{}).id;
              return (
                <div key={i} onClick={()=>cid&&go&&go('client-detail',{id:cid})} style={{ display:'flex', gap:12, padding:'12px', borderRadius:11, background:'var(--bg)', cursor: cid?'pointer':'default', alignItems:'center' }}>
                  <span style={{ width:38, height:38, borderRadius:10, background:t.bg, color:t.color, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}><Icon name={t.icon} size={18} /></span>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:13.5, fontWeight:600, color:'var(--ink)' }}>{e.client}</div>
                    <div style={{ fontSize:12, color:'var(--muted)' }}>{t.label} · {e.route}</div>
                  </div>
                  <div style={{ textAlign:'right', flexShrink:0 }}>
                    <div style={{ fontSize:12.5, fontWeight:600, color:'var(--ink)' }}>{e.time}</div>
                    <div style={{ fontSize:11, color:'var(--faint)' }}>{e.crew}</div>
                  </div>
                </div>
              );
            })}
          </div>}
    </div>
  );
  if (mobile) return <div style={{ display:'flex', flexDirection:'column', gap:16 }}>{grid}{dayPanel}</div>;
  return <div style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:18, alignItems:'start' }}>{grid}{dayPanel}</div>;
}

/* ============== TIMELINE D'ACTIVITÉ ============== */
function ActivityTimeline({ events }) {
  return (
    <div className="card card-pad">
      <span className="section-title" style={{ fontSize:16, display:'block', marginBottom:16 }}>Activité du dossier</span>
      <div>
        {events.map((e,i)=>{
          const last = i===events.length-1;
          return (
            <div key={i} style={{ display:'flex', gap:13, position:'relative', paddingBottom: last?0:16 }}>
              {!last && <div style={{ position:'absolute', left:12, top:24, bottom:0, width:2, background:'var(--border)' }} />}
              <span style={{ width:26, height:26, borderRadius:'50%', flexShrink:0, zIndex:1, display:'flex', alignItems:'center', justifyContent:'center', background:(e.color||'var(--navy)')+'1c', color:e.color||'var(--navy)' }}><Icon name={e.icon} size={14} /></span>
              <div style={{ paddingTop:2 }}>
                <div style={{ fontSize:13.5, fontWeight:500, color:'var(--ink)' }}>{e.label}</div>
                <div style={{ fontSize:12, color:'var(--muted)', marginTop:1 }}>{e.time}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ============== NOTES INTERNES ============== */
function InternalNotes({ notesApi, showToast }) {
  const [draft, setDraft] = useG('');
  const add = ()=>{ const t=draft.trim(); if(!t) return; notesApi.add(t); setDraft(''); showToast && showToast('Note interne ajoutée'); };
  return (
    <div className="card card-pad">
      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
        <span className="section-title" style={{ fontSize:16 }}>Notes internes</span>
        <span style={{ fontSize:10.5, fontWeight:600, letterSpacing:'.05em', textTransform:'uppercase', color:'var(--accepte)', background:'var(--accepte-bg)', padding:'2px 7px', borderRadius:5 }}>Privé</span>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:9, marginBottom:12 }}>
        {notesApi.notes.length===0 && <div style={{ fontSize:13, color:'var(--faint)', padding:'6px 0' }}>Aucune note pour ce dossier.</div>}
        {notesApi.notes.map((n,i)=>(
          <div key={i} style={{ display:'flex', gap:10, background:'var(--bg)', borderRadius:10, padding:'11px 13px' }}>
            <Avatar initials={n.who} size={26} color="var(--ink-2)" />
            <div style={{ flex:1 }}><div style={{ fontSize:13, color:'var(--ink)', lineHeight:1.45 }}>{n.text}</div>
              <div style={{ fontSize:11, color:'var(--faint)', marginTop:3 }}>{n.time}</div></div>
          </div>
        ))}
      </div>
      <div style={{ display:'flex', gap:9 }}>
        <input className="input" value={draft} onChange={e=>setDraft(e.target.value)} onKeyDown={e=>{ if(e.key==='Enter') add(); }} placeholder="Ajouter une note interne…" style={{ flex:1, height:42 }} />
        <button className="btn btn-navy" style={{ width:46, padding:0, height:42 }} onClick={add}><Icon name="plus" size={18} /></button>
      </div>
    </div>
  );
}

Object.assign(window, { StaffLogin, ChatPanel, AdminMessages, PlanningCalendar, ActivityTimeline, InternalNotes });
