// Bellia — Module RH : planning visuel hebdomadaire avec drag & drop

const EMPLOYEES = [
  { id: 'e1',  name: 'Aïcha Benamar',     role: 'Chef de cuisine', dept: 'cuisine', initials: 'AB', c: '#C97849', contractH: 39 },
  { id: 'e2',  name: 'Pierre Dubois',     role: 'Second de cuisine', dept: 'cuisine', initials: 'PD', c: '#7FB069', contractH: 39 },
  { id: 'e3',  name: 'Léa Moreau',        role: 'Cheffe de partie', dept: 'cuisine', initials: 'LM', c: '#D9923B', contractH: 35 },
  { id: 'e4',  name: 'Karim Bensalem',    role: 'Cuisinier',       dept: 'cuisine', initials: 'KB', c: '#5B8DEF', contractH: 35 },
  { id: 'e5',  name: 'Sofia Lopez',       role: 'Commis',          dept: 'cuisine', initials: 'SL', c: '#A87AC9', contractH: 35 },
  { id: 'e6',  name: 'Marc Chevalier',    role: 'Plongeur',        dept: 'cuisine', initials: 'MC', c: '#7BA6B5', contractH: 24 },
  { id: 'e7',  name: 'Clara Bertin',      role: 'Cheffe de rang',  dept: 'salle',   initials: 'CB', c: '#C97849', contractH: 39 },
  { id: 'e8',  name: 'Tom Lefèvre',       role: 'Serveur',         dept: 'salle',   initials: 'TL', c: '#7FB069', contractH: 35 },
  { id: 'e9',  name: 'Yasmine Ferrand',   role: 'Serveuse',        dept: 'salle',   initials: 'YF', c: '#D9923B', contractH: 35 },
  { id: 'e10', name: 'Hugo Martin',       role: 'Runner',          dept: 'salle',   initials: 'HM', c: '#5B8DEF', contractH: 24 },
];

const DAYS = ['Lun. 11', 'Mar. 12', 'Mer. 13', 'Jeu. 14', 'Ven. 15', 'Sam. 16', 'Dim. 17'];
const SHIFT_TYPES = {
  midi:    { l: 'Midi',     start: '11:00', end: '15:00', hours: 4, bg: C.orangeWh,   fg: C.orangeDp, bar: C.orange },
  soir:    { l: 'Soir',     start: '18:30', end: '23:00', hours: 4.5, bg: '#F1E7D5',  fg: C.ink2,     bar: C.ink2 },
  continu: { l: 'Continu',  start: '11:00', end: '23:00', hours: 9, bg: '#FBE9D5',    fg: C.warn,     bar: C.warn },
  prep:    { l: 'Prep.',    start: '08:00', end: '12:00', hours: 4, bg: C.okSft,      fg: C.ok,       bar: C.ok },
  off:     { l: 'Repos',    start: '',      end: '',      hours: 0, bg: 'transparent', fg: C.mute,    bar: C.line },
};

// Génère un planning de base
const initShifts = () => {
  const out = {};
  EMPLOYEES.forEach(e => {
    out[e.id] = DAYS.map((_, di) => {
      const isWeekend = di >= 5;
      const isMonday = di === 0;
      if (isMonday && e.id === 'e6') return 'off';
      if (isMonday && (e.id === 'e3' || e.id === 'e8')) return 'off';
      if (di === 2 && e.id === 'e5') return 'off';
      if (di === 3 && e.id === 'e10') return 'off';
      if (di === 4 && e.id === 'e2') return 'off';
      if (e.dept === 'cuisine') {
        if (e.id === 'e1' || e.id === 'e2') return isWeekend ? 'continu' : (di % 2 === 0 ? 'midi' : 'soir');
        if (e.id === 'e6') return isWeekend ? 'soir' : 'midi';
        return isWeekend ? 'continu' : (di % 2 === 1 ? 'soir' : 'midi');
      } else {
        if (e.id === 'e7') return isWeekend ? 'continu' : (di % 2 === 0 ? 'soir' : 'midi');
        return isWeekend ? 'continu' : (di % 2 === 1 ? 'midi' : 'soir');
      }
    });
  });
  return out;
};

const RhScreen = ({ onNav }) => {
  const [shifts, setShifts] = React.useState(initShifts);
  const [dept, setDept] = React.useState('tous');
  const [dragging, setDragging] = React.useState(null);  // { type, fromEmp?, fromDay? }
  const [hover, setHover] = React.useState(null);        // { emp, day }
  const [selectedShift, setSelectedShift] = React.useState(null);  // { emp, day }

  const employees = EMPLOYEES.filter(e => dept === 'tous' || e.dept === dept);

  // Compute totals
  const empHours = React.useMemo(() => {
    const out = {};
    EMPLOYEES.forEach(e => {
      out[e.id] = (shifts[e.id] || []).reduce((a, s) => a + SHIFT_TYPES[s].hours, 0);
    });
    return out;
  }, [shifts]);

  const dayCoverage = React.useMemo(() => DAYS.map((_, di) => {
    let midi = 0, soir = 0;
    EMPLOYEES.forEach(e => {
      const s = shifts[e.id]?.[di];
      if (s === 'midi' || s === 'continu' || s === 'prep') midi++;
      if (s === 'soir' || s === 'continu') soir++;
    });
    return { midi, soir };
  }), [shifts]);

  const totalHours = Object.values(empHours).reduce((a, b) => a + b, 0);
  const totalMass = totalHours * 16.5;  // taux moyen indicatif

  // DnD handlers
  const handleDrop = (toEmp, toDay) => {
    if (!dragging) return;
    setShifts(prev => {
      const next = { ...prev, [toEmp]: [...prev[toEmp]] };
      if (dragging.fromEmp != null && dragging.fromDay != null) {
        // swap
        const fromShift = next[dragging.fromEmp]?.[dragging.fromDay];
        const toShift = next[toEmp]?.[toDay];
        next[dragging.fromEmp] = [...next[dragging.fromEmp]];
        next[dragging.fromEmp][dragging.fromDay] = toShift;
        next[toEmp][toDay] = fromShift;
      } else {
        next[toEmp][toDay] = dragging.type;
      }
      return next;
    });
    setDragging(null);
    setHover(null);
  };

  return (
    <PageShell current="rh" onNav={onNav}>
      <Header
        title="Planning de la semaine"
        subtitle="Semaine du 11 au 17 mai 2026 · République"
        right={<>
          <Btn kind="ghost" icon={<Icon name="sparkles" size={14} color={C.orangeDp} />}>Suggérer (IA)</Btn>
          <Btn kind="ghost" icon={<Icon name="download" size={14} color={C.ink2} />}>Exporter</Btn>
          <Btn kind="primary" icon={<Icon name="check" size={14} stroke={2.4} />}>Publier</Btn>
        </>}
      />

      {/* ===== Top bar : KPI + toolbar ===== */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 18 }}>
        <BigStat label="Heures planifiées" value={`${num(Math.round(totalHours))} h`} count={`/ ${num(EMPLOYEES.reduce((a, e) => a + e.contractH, 0))} h contrat`} accent="accent" />
        <BigStat label="Masse salariale" value={eur(totalMass)} count={pct(34.2) + ' du CA prévu'} accent="warn" />
        <BigStat label="Couverture midi" value={`${dayCoverage.filter(d => d.midi >= 5).length} / 7 j`} count={dayCoverage.some(d => d.midi < 4) ? 'Sous-effectif détecté' : 'Tous les services couverts'} accent={dayCoverage.some(d => d.midi < 4) ? 'err' : 'ok'} />
        <BigStat label="Repos hebdo" value="9 / 10" count="K. Bensalem sans repos consécutif" accent="warn" />
      </div>

      {/* Week navigator + filters */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <button style={navBtnStyle} aria-label="Semaine précédente"><Icon name="chevLeft" size={14} color={C.ink2} /></button>
          <div style={{ padding: '8px 16px', background: C.card, border: `1px solid ${C.line}`, borderRadius: 999, fontSize: 12, fontWeight: 600, color: C.ink, display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <Icon name="cal" size={13} color={C.orangeDp} /> Sem. 20 · 11 au 17 mai
          </div>
          <button style={navBtnStyle} aria-label="Semaine suivante"><Icon name="chevRight" size={14} color={C.ink2} /></button>
        </div>

        <div style={{ display: 'inline-flex', padding: 4, background: C.card, border: `1px solid ${C.line}`, borderRadius: 999, gap: 2 }}>
          {[
            { id: 'tous', l: 'Toute l\'équipe', n: EMPLOYEES.length },
            { id: 'cuisine', l: 'Cuisine', n: EMPLOYEES.filter(e => e.dept === 'cuisine').length },
            { id: 'salle',   l: 'Salle',   n: EMPLOYEES.filter(e => e.dept === 'salle').length },
          ].map(t => {
            const active = dept === t.id;
            return (
              <button key={t.id} onClick={() => setDept(t.id)} style={{
                padding: '7px 14px', borderRadius: 999, background: active ? C.orange : 'transparent',
                color: active ? '#fff' : C.mute, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
                fontSize: 11, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 5,
              }}>{t.l} <span style={{ fontSize: 10, opacity: 0.85 }}>{t.n}</span></button>
            );
          })}
        </div>
      </div>

      {/* ===== Planning grid ===== */}
      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr 160px', gap: 0, background: C.card, border: `1px solid ${C.line}`, borderRadius: 22, overflow: 'hidden' }}>
        {/* HEADER ROW */}
        <div style={{ padding: '14px 18px', borderBottom: `1px solid ${C.line}`, background: C.cardWash, fontSize: 11, fontWeight: 700, color: C.mute, letterSpacing: 0.5, textTransform: 'uppercase' }}>Équipe</div>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${DAYS.length}, 1fr)`, borderBottom: `1px solid ${C.line}`, background: C.cardWash }}>
          {DAYS.map((d, i) => (
            <div key={d} style={{ padding: '10px 8px', textAlign: 'center', borderLeft: `1px solid ${C.lineSoft}` }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: C.ink, letterSpacing: -0.2 }}>{d}</div>
              <div style={{ fontSize: 10, color: dayCoverage[i].midi < 4 ? C.err : C.mute, marginTop: 3, fontWeight: 600 }}>
                {dayCoverage[i].midi}M · {dayCoverage[i].soir}S
              </div>
            </div>
          ))}
        </div>
        <div style={{ padding: '14px 16px', borderBottom: `1px solid ${C.line}`, background: C.cardWash, fontSize: 11, fontWeight: 700, color: C.mute, letterSpacing: 0.5, textTransform: 'uppercase', textAlign: 'right' }}>Heures sem.</div>

        {/* ROWS */}
        {employees.map((e, ri) => {
          const hours = empHours[e.id];
          const over = hours > e.contractH;
          const under = hours < e.contractH - 4;
          return (
            <React.Fragment key={e.id}>
              {/* employee cell */}
              <div style={{
                padding: '12px 18px', display: 'flex', alignItems: 'center', gap: 10,
                borderBottom: ri === employees.length - 1 ? 'none' : `1px solid ${C.lineSoft}`,
                borderRight: `1px solid ${C.line}`,
              }}>
                <Avatar initials={e.initials} c={e.c} size={32} />
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: C.ink, letterSpacing: -0.1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.name}</div>
                  <div style={{ fontSize: 10, color: C.mute, marginTop: 1 }}>{e.role}</div>
                </div>
              </div>

              {/* shift cells */}
              <div style={{ display: 'grid', gridTemplateColumns: `repeat(${DAYS.length}, 1fr)`, borderBottom: ri === employees.length - 1 ? 'none' : `1px solid ${C.lineSoft}` }}>
                {DAYS.map((_, di) => {
                  const shift = shifts[e.id]?.[di] || 'off';
                  const meta = SHIFT_TYPES[shift];
                  const isHover = hover && hover.emp === e.id && hover.day === di;
                  const isSelected = selectedShift && selectedShift.emp === e.id && selectedShift.day === di;
                  return (
                    <div key={di}
                      onDragOver={(ev) => { ev.preventDefault(); setHover({ emp: e.id, day: di }); }}
                      onDragLeave={() => setHover(h => h && h.emp === e.id && h.day === di ? null : h)}
                      onDrop={() => handleDrop(e.id, di)}
                      onClick={() => setSelectedShift({ emp: e.id, day: di })}
                      style={{
                        padding: 6, borderLeft: `1px solid ${C.lineSoft}`, minHeight: 64,
                        background: isHover ? C.orangeWh : 'transparent',
                        cursor: 'pointer', display: 'flex',
                      }}
                    >
                      {shift === 'off' ? (
                        <div style={{
                          width: '100%', borderRadius: 8, border: `1px dashed ${C.line}`,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          color: C.mute2, fontSize: 10, fontWeight: 600,
                        }}>Repos</div>
                      ) : (
                        <div
                          draggable
                          onDragStart={(ev) => { ev.dataTransfer.effectAllowed = 'move'; setDragging({ type: shift, fromEmp: e.id, fromDay: di }); }}
                          onDragEnd={() => setDragging(null)}
                          style={{
                            width: '100%', borderRadius: 10, padding: '8px 8px',
                            background: meta.bg, borderLeft: `3px solid ${meta.bar}`,
                            display: 'flex', flexDirection: 'column', gap: 2, cursor: 'grab',
                            boxShadow: isSelected ? `0 0 0 2px ${C.orange}` : 'none',
                            transition: 'transform .12s ease',
                          }}
                          onMouseEnter={ev => ev.currentTarget.style.transform = 'translateY(-1px)'}
                          onMouseLeave={ev => ev.currentTarget.style.transform = 'translateY(0)'}
                        >
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <span style={{ fontSize: 10, fontWeight: 700, color: meta.fg, letterSpacing: 0.2 }}>{meta.l}</span>
                            <span style={{ fontSize: 9, color: meta.fg, opacity: 0.7, fontVariantNumeric: 'tabular-nums' }}>{meta.hours}h</span>
                          </div>
                          <div style={{ fontSize: 10, color: meta.fg, fontWeight: 600, fontVariantNumeric: 'tabular-nums', opacity: 0.85 }}>{meta.start}–{meta.end}</div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              {/* hours summary */}
              <div style={{
                padding: '12px 16px', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', justifyContent: 'center',
                borderBottom: ri === employees.length - 1 ? 'none' : `1px solid ${C.lineSoft}`,
                borderLeft: `1px solid ${C.line}`,
              }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: over ? C.err : under ? C.warn : C.ink, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3 }}>{hours} h</div>
                <div style={{ fontSize: 10, color: C.mute, fontVariantNumeric: 'tabular-nums', marginTop: 2 }}>contrat {e.contractH} h</div>
                <div style={{ width: '100%', height: 4, background: C.cardSoft, borderRadius: 999, marginTop: 6, overflow: 'hidden' }}>
                  <div style={{ width: `${Math.min(100, (hours / e.contractH) * 100)}%`, height: '100%', background: over ? C.err : under ? C.warn : C.ok, borderRadius: 999 }} />
                </div>
              </div>
            </React.Fragment>
          );
        })}
      </div>

      {/* ===== Bottom: palette + alerts ===== */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16, marginTop: 18 }}>
        {/* Palette - drag from here */}
        <div style={{ background: C.cardWash, border: `1px solid ${C.line}`, borderRadius: 18, padding: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <SectionLabel>Palette de créneaux</SectionLabel>
            <span style={{ fontSize: 10, color: C.mute }}>Glissez sur une case pour ajouter</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
            {['midi', 'soir', 'continu', 'prep'].map(k => {
              const meta = SHIFT_TYPES[k];
              return (
                <div key={k} draggable
                  onDragStart={(ev) => { ev.dataTransfer.effectAllowed = 'copy'; setDragging({ type: k }); }}
                  onDragEnd={() => setDragging(null)}
                  style={{
                    padding: '10px 12px', background: meta.bg, borderLeft: `3px solid ${meta.bar}`, borderRadius: 10,
                    cursor: 'grab', display: 'flex', flexDirection: 'column', gap: 4,
                  }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span style={{ fontSize: 11, fontWeight: 700, color: meta.fg, letterSpacing: 0.2 }}>{meta.l}</span>
                    <span style={{ fontSize: 10, color: meta.fg, opacity: 0.7, fontVariantNumeric: 'tabular-nums' }}>{meta.hours} h</span>
                  </div>
                  <div style={{ fontSize: 10, color: meta.fg, fontWeight: 600, opacity: 0.85, fontVariantNumeric: 'tabular-nums' }}>{meta.start} – {meta.end}</div>
                </div>
              );
            })}
          </div>
          <div style={{ marginTop: 12, fontSize: 11, color: C.mute, display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="sparkles" size={12} color={C.orangeDp} /> Astuce : glissez un créneau d'une cellule à une autre pour échanger.
          </div>
        </div>

        {/* Alerts panel */}
        <div style={{ background: C.cardWash, border: `1px solid ${C.line}`, borderRadius: 18, padding: 16 }}>
          <SectionLabel>Alertes du planning</SectionLabel>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            <AlertRow kind="err"  t="Sous-effectif jeudi midi" v="3 personnes en cuisine au lieu de 4" />
            <AlertRow kind="warn" t="K. Bensalem sans repos consécutif" v="Ajouter un repos lun. ou mar." />
            <AlertRow kind="warn" t="Heures supplémentaires détectées" v="A. Benamar : 42 h (+3 h vs contrat)" />
            <AlertRow kind="ok"   t="Couverture week-end optimale" v="6 personnes sam. et dim." />
          </div>
        </div>
      </div>
    </PageShell>
  );
};

const navBtnStyle = {
  width: 38, height: 38, borderRadius: 999, background: C.card, border: `1px solid ${C.line}`,
  display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
};

const AlertRow = ({ kind, t, v }) => {
  const map = { err: { c: C.err, bg: C.errSft, icon: 'alertT' }, warn: { c: C.warn, bg: C.warnSft, icon: 'alertC' }, ok: { c: C.ok, bg: C.okSft, icon: 'checkC' } };
  const m = map[kind];
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 12px', borderRadius: 12, background: C.card, border: `1px solid ${C.lineSoft}` }}>
      <div style={{ width: 26, height: 26, borderRadius: 999, background: m.bg, color: m.c, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon name={m.icon} size={13} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 700, color: C.ink, letterSpacing: -0.1 }}>{t}</div>
        <div style={{ fontSize: 11, color: C.mute, marginTop: 2 }}>{v}</div>
      </div>
    </div>
  );
};

window.RhScreen = RhScreen;
