// ============================================================
// ЛИНИЯ ЖИЗНИ — Staff Board + Reports
// ============================================================

/* ── STAFF BOARD ────────────────────────────────────────────── */
function StaffView({ schedule, procedures }) {
  const staffList = window.STAFF_LIST || [];

  const blockedCells = React.useMemo(() => {
    const set = new Set();
    schedule.forEach(entry => {
      const span = Math.max(1, Math.ceil((findStageForEntryV(entry)?.duration || 30) / 30));
      const startIdx = getSlotIndex(entry.slot);
      for (let i = 1; i < span; i++) {
        if (startIdx + i < TIME_SLOTS.length)
          set.add(`${TIME_SLOTS[startIdx + i]}::${entry.staffId}`);
      }
    });
    return set;
  }, [schedule]);

  function findStageForEntryV(entry) {
    for (const pt of (window.PROCEDURE_TYPES||[])) {
      const s = pt.stages.find(s => s.id === entry.stageId);
      if (s) return s;
    }
    return null;
  }

  const thBase = { padding:'8px 6px', fontSize:11, fontWeight:700, textAlign:'center', borderBottom:`2px solid ${T.border}`, position:'sticky', top:0, zIndex:5, background:'#F8FAFC', fontFamily:T.ff, color:T.text1, whiteSpace:'nowrap', border:`1px solid ${T.border}` };

  return (
    <div style={{ flex:1, overflow:'auto' }}>
      <div style={{ padding:'12px 20px 10px', borderBottom:`1px solid ${T.border}`, background:'#fff', position:'sticky', top:0, zIndex:6 }}>
        <span style={{ fontSize:12, color:T.text3, fontFamily:T.ffBody }}>Только просмотр — данные из вкладки ОСНОВ.ДОСКА</span>
      </div>
      <table style={{ borderCollapse:'collapse', width:'100%', tableLayout:'fixed', minWidth:700 }}>
        <colgroup>
          <col style={{ width:54 }} />
          {staffList.map(s => <col key={s.id} />)}
        </colgroup>
        <thead>
          <tr>
            <th style={thBase}></th>
            {staffList.map(s => (
              <th key={s.id} style={thBase}>
                <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:3 }}>
                  <div style={{ width:28, height:28, borderRadius:14, background:s.color, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, fontFamily:T.ff }}>{s.initials}</div>
                  <div style={{ fontSize:10, fontWeight:600 }}>{s.name.split(' ')[0]}</div>
                  <div style={{ fontSize:9, fontWeight:400, color:T.text3 }}>{s.roleLabel}</div>
                </div>
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {TIME_SLOTS.map(slot => {
            const isHour = slot.endsWith(':00');
            return (
              <tr key={slot} style={{ background:isHour?'#FAFBFD':'#fff' }}>
                <td style={{ fontSize:11, fontWeight:isHour?700:400, color:isHour?T.text2:T.text3, textAlign:'center', borderRight:`2px solid ${T.border}`, padding:'0 6px', height:38, fontFamily:T.ff }}>
                  {isHour ? slot : <span style={{ fontSize:10 }}>{slot}</span>}
                </td>
                {staffList.map(staff => {
                  if (blockedCells.has(`${slot}::${staff.id}`)) return null;
                  const entry = schedule.find(e => e.staffId === staff.id && e.slot === slot);
                  if (!entry) return <td key={staff.id} style={{ height:38, border:`1px solid ${T.border}` }}></td>;

                  const proc = procedures.find(p => p.id === entry.procId);
                  const pt   = (window.PROCEDURE_TYPES||[]).find(t => t.id === proc?.typeId);
                  const stage = pt?.stages?.find(s => s.id === entry.stageId);
                  const eq    = (window.EQUIPMENT_LIST||[]).find(e => e.id === entry.eqId);
                  const span  = Math.max(1, Math.ceil((stage?.duration||30)/30));

                  return (
                    <td key={staff.id} rowSpan={span} style={{ padding:3, border:`1px solid ${T.border}`, verticalAlign:'top', height:38*span }}>
                      <div style={{ background:`${pt?.color||'#94A3B8'}15`, borderLeft:`3px solid ${pt?.color||'#94A3B8'}`, borderRadius:7, padding:'4px 7px', height:'100%', boxSizing:'border-box' }}>
                        <div style={{ fontSize:10, fontWeight:700, color:pt?.color||T.text1, fontFamily:T.ff, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{pt?.name||'—'}</div>
                        <div style={{ fontSize:10, color:T.text2, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{stage?.name||'—'}</div>
                        <div style={{ fontSize:10, color:T.text3, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{eq?.name||'—'}</div>
                      </div>
                    </td>
                  );
                })}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

/* ── Helpers for reports ────────────────────────────────────── */
function fmtH(min) {
  const h=Math.floor(min/60), m=min%60;
  return h>0 ? (m>0?`${h}ч ${m}м`:`${h}ч`) : `${m}м`;
}

function LoadBar({ value, max }) {
  const pct = max > 0 ? Math.min(100, Math.round(value/max*100)) : 0;
  const color = pct>70 ? T.red.dot : pct>40 ? T.amber.dot : T.teal;
  return (
    <div style={{ display:'flex', alignItems:'center', gap:7, justifyContent:'center' }}>
      <div style={{ width:52, height:5, background:'#F1F5F9', borderRadius:3, overflow:'hidden', flexShrink:0 }}>
        <div style={{ width:`${pct}%`, height:'100%', background:color, borderRadius:3 }}></div>
      </div>
      <span style={{ fontSize:12, fontWeight:700, color, minWidth:34, fontFamily:T.ff }}>{fmtH(value)}</span>
    </div>
  );
}

function ReportDatePicker({ onLoad, label }) {
  const today = new Date();
  const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
  const weekAgo = new Date(today); weekAgo.setDate(weekAgo.getDate()-7);
  const [from, setFrom] = React.useState(fmt(weekAgo));
  const [to,   setTo]   = React.useState(fmt(today));
  const [groupBy, setGroupBy] = React.useState('day');
  const [loading, setLoading] = React.useState(false);

  const handleLoad = async () => {
    setLoading(true);
    try { await onLoad(from, to, groupBy); } finally { setLoading(false); }
  };

  const inp2 = { border:`1.5px solid ${T.border}`, borderRadius:8, padding:'7px 10px', fontSize:13, color:T.text1, outline:'none', fontFamily:'inherit', background:'#FAFBFC' };
  const groupBtn = (val, lbl) => ({
    padding:'5px 12px', borderRadius:7, border:`1.5px solid ${groupBy===val?T.navy:T.border}`,
    background: groupBy===val ? T.navy : 'transparent',
    color: groupBy===val ? '#fff' : T.text3,
    cursor:'pointer', fontSize:12, fontWeight:700, fontFamily:T.ff,
  });

  return (
    <div style={{ display:'flex', alignItems:'center', gap:10, padding:'14px 24px', borderBottom:`1px solid ${T.border}`, background:'#fff', position:'sticky', top:0, zIndex:6, flexWrap:'wrap' }}>
      <span style={{ fontSize:12, color:T.text3, fontFamily:T.ffBody }}>Период:</span>
      <label style={{ display:'flex', alignItems:'center', gap:6, fontSize:13, color:T.text2 }}>С <input type="date" value={from} onChange={e=>setFrom(e.target.value)} style={inp2} /></label>
      <label style={{ display:'flex', alignItems:'center', gap:6, fontSize:13, color:T.text2 }}>По <input type="date" value={to} onChange={e=>setTo(e.target.value)} style={inp2} /></label>
      <span style={{ fontSize:12, color:T.text3, fontFamily:T.ffBody, marginLeft:6 }}>Группировка:</span>
      <button style={groupBtn('day','По дням')} onClick={() => setGroupBy('day')}>По дням</button>
      <button style={groupBtn('month','По месяцам')} onClick={() => setGroupBy('month')}>По месяцам</button>
      <Btn small onClick={handleLoad} disabled={loading}>{loading?'Загрузка…':'Загрузить'}</Btn>
    </div>
  );
}

function fmtPeriod(workDate, groupBy) {
  const d = new Date(workDate+'T12:00:00');
  if (groupBy === 'month') {
    return d.toLocaleDateString('ru-RU', { year:'numeric', month:'long' });
  }
  return d.toLocaleDateString('ru-RU', { day:'numeric', month:'short' });
}

/* ── STAFF REPORT ───────────────────────────────────────────── */
function StaffReport() {
  const [days, setDays] = React.useState(null);
  const [expanded, setExpanded] = React.useState({});
  const [groupBy, setGroupBy] = React.useState('day');

  const load = async (from, to, gb='day') => {
    setGroupBy(gb);
    const data = await LL.loadReportEmployees(from, to, gb);
    setDays(data || []);
    setExpanded({});
  };

  const toggle = d => setExpanded(p => ({...p,[d]:!p[d]}));

  // Collect all unique employee names from loaded data
  const allEmps = React.useMemo(() => {
    if (!days) return [];
    const names = new Set();
    days.forEach(day => (day.employees||[]).forEach(e => names.add(e.employee_name)));
    return [...names].sort();
  }, [days]);

  const maxMin = TIME_SLOTS.length * 30;
  const thBase = { padding:'10px 12px', fontSize:11, fontWeight:700, color:T.text3, textAlign:'center', borderBottom:`2px solid ${T.border}`, whiteSpace:'nowrap', background:'#F8FAFC', fontFamily:T.ff };
  const td = { padding:'9px 12px', fontSize:13, textAlign:'center', borderBottom:`1px solid #F1F5F9`, color:T.text1 };

  return (
    <div style={{ flex:1, overflow:'auto', display:'flex', flexDirection:'column' }}>
      <ReportDatePicker onLoad={load} />
      <div style={{ flex:1, overflow:'auto', padding:'24px' }}>
        <div style={{ marginBottom:22 }}>
          <h2 style={{ fontSize:20, fontWeight:800, color:T.text1, margin:0, fontFamily:T.ff, letterSpacing:'-0.04em' }}>Загруженность сотрудников</h2>
          <p style={{ fontSize:13, color:T.text3, marginTop:5, fontFamily:T.ffBody }}>Суммарные трудозатраты по дням · нажмите строку для детализации</p>
        </div>
        {days === null && <div style={{ textAlign:'center', color:T.text3, marginTop:60, fontFamily:T.ffBody }}>Выберите период и нажмите «Загрузить»</div>}
        {days !== null && days.length === 0 && <div style={{ textAlign:'center', color:T.text3, marginTop:60, fontFamily:T.ffBody }}>Нет данных за выбранный период</div>}
        {days !== null && days.length > 0 && (
          <div style={{ background:'#fff', borderRadius:16, border:`1.5px solid ${T.border}`, overflow:'hidden' }}>
            <table style={{ width:'100%', borderCollapse:'collapse' }}>
              <thead>
                <tr>
                  <th style={{ ...thBase, textAlign:'left', paddingLeft:20 }}>Дата</th>
                  {allEmps.map(name => <th key={name} style={thBase}><div style={{ maxWidth:80, margin:'0 auto', lineHeight:1.3 }}>{name}</div></th>)}
                </tr>
              </thead>
              <tbody>
                {days.map(day => {
                  const isOpen = expanded[day.work_date];
                  const dateLabel = fmtPeriod(day.work_date, groupBy);
                  return (
                    <React.Fragment key={day.work_date}>
                      <tr onClick={() => toggle(day.work_date)} style={{ cursor:'pointer', background:isOpen?'#F0F9FF':'#fff' }}
                        onMouseEnter={e=>{ if(!isOpen) e.currentTarget.style.background='#F8FAFC'; }}
                        onMouseLeave={e=>{ if(!isOpen) e.currentTarget.style.background='#fff'; }}>
                        <td style={{ ...td, textAlign:'left', paddingLeft:20, fontWeight:700, fontFamily:T.ff }}>
                          <span style={{ marginRight:8, fontSize:11, color:T.text3 }}>{isOpen?'▼':'▶'}</span>{dateLabel}
                        </td>
                        {allEmps.map(name => {
                          const emp = (day.employees||[]).find(e => e.employee_name === name);
                          return <td key={name} style={td}>{emp ? <LoadBar value={emp.total_minutes} max={maxMin*(groupBy==='month'?20:1)} /> : <span style={{ color:T.border }}>—</span>}</td>;
                        })}
                      </tr>
                      {isOpen && (day.employees||[]).flatMap(emp =>
                        (emp.slots||[]).map((slot, si) => (
                          <tr key={`${emp.employee_name}-${si}`} style={{ background:'#F8FBFF' }}>
                            <td style={{ ...td, paddingLeft:44, color:T.text3, fontSize:12 }}>{slot.start_time}–{slot.end_time}</td>
                            {allEmps.map(name => {
                              if (name !== emp.employee_name) return <td key={name} style={{ ...td, fontSize:11 }}><span style={{ color:'#E2E8F0' }}>·</span></td>;
                              return (
                                <td key={name} style={{ ...td, fontSize:11 }}>
                                  <span style={{ background:`${T.blue.bg}`, color:T.blue.text, padding:'2px 8px', borderRadius:20, fontWeight:700, fontFamily:T.ff, fontSize:11 }}>
                                    {slot.step_name}
                                  </span>
                                  <div style={{ fontSize:10, color:T.text3, marginTop:2 }}>{slot.procedure_name}</div>
                                </td>
                              );
                            })}
                          </tr>
                        ))
                      )}
                    </React.Fragment>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

/* ── EQUIPMENT REPORT ───────────────────────────────────────── */
function EquipmentReport() {
  const [days, setDays] = React.useState(null);
  const [expanded, setExpanded] = React.useState({});
  const [groupBy, setGroupBy] = React.useState('day');

  const load = async (from, to, gb='day') => {
    setGroupBy(gb);
    const data = await LL.loadReportEquipment(from, to, gb);
    setDays(data || []);
    setExpanded({});
  };

  const toggle = d => setExpanded(p => ({...p,[d]:!p[d]}));

  const allEq = React.useMemo(() => {
    if (!days) return [];
    const names = new Set();
    days.forEach(day => (day.equipment||[]).forEach(e => names.add(e.equipment_name)));
    return [...names].sort();
  }, [days]);

  const maxMin = TIME_SLOTS.length * 30;
  const thBase = { padding:'9px 8px', fontSize:10, fontWeight:700, color:T.text3, textAlign:'center', borderBottom:`2px solid ${T.border}`, background:'#F8FAFC', fontFamily:T.ff };
  const td = { padding:'8px 10px', fontSize:12, textAlign:'center', borderBottom:`1px solid #F1F5F9` };

  return (
    <div style={{ flex:1, overflow:'auto', display:'flex', flexDirection:'column' }}>
      <ReportDatePicker onLoad={load} />
      <div style={{ flex:1, overflow:'auto', padding:'24px' }}>
        <div style={{ marginBottom:22 }}>
          <h2 style={{ fontSize:20, fontWeight:800, color:T.text1, margin:0, fontFamily:T.ff, letterSpacing:'-0.04em' }}>Загруженность оборудования</h2>
          <p style={{ fontSize:13, color:T.text3, marginTop:5, fontFamily:T.ffBody }}>Суммарная занятость по дням · нажмите строку для детализации</p>
        </div>
        {days === null && <div style={{ textAlign:'center', color:T.text3, marginTop:60, fontFamily:T.ffBody }}>Выберите период и нажмите «Загрузить»</div>}
        {days !== null && days.length === 0 && <div style={{ textAlign:'center', color:T.text3, marginTop:60, fontFamily:T.ffBody }}>Нет данных за выбранный период</div>}
        {days !== null && days.length > 0 && (
          <div style={{ background:'#fff', borderRadius:16, border:`1.5px solid ${T.border}`, overflow:'hidden' }}>
            <table style={{ width:'100%', borderCollapse:'collapse' }}>
              <thead>
                <tr>
                  <th style={{ ...thBase, textAlign:'left', paddingLeft:20 }}>Дата</th>
                  {allEq.map(name => <th key={name} style={thBase}><div style={{ fontSize:10, lineHeight:1.3, maxWidth:72, margin:'0 auto' }}>{name}</div></th>)}
                </tr>
              </thead>
              <tbody>
                {days.map(day => {
                  const isOpen = expanded[day.work_date];
                  const dateLabel = fmtPeriod(day.work_date, groupBy);
                  return (
                    <React.Fragment key={day.work_date}>
                      <tr onClick={() => toggle(day.work_date)} style={{ cursor:'pointer', background:isOpen?'#F0F9FF':'#fff' }}
                        onMouseEnter={e=>{ if(!isOpen) e.currentTarget.style.background='#F8FAFC'; }}
                        onMouseLeave={e=>{ if(!isOpen) e.currentTarget.style.background='#fff'; }}>
                        <td style={{ ...td, textAlign:'left', paddingLeft:20, fontWeight:700, fontFamily:T.ff, color:T.text1 }}>
                          <span style={{ marginRight:8, fontSize:11, color:T.text3 }}>{isOpen?'▼':'▶'}</span>{dateLabel}
                        </td>
                        {allEq.map(name => {
                          const eq = (day.equipment||[]).find(e => e.equipment_name === name);
                          return <td key={name} style={td}>{eq ? <LoadBar value={eq.total_minutes} max={maxMin*(groupBy==='month'?20:1)} /> : <span style={{ color:'#E2E8F0' }}>—</span>}</td>;
                        })}
                      </tr>
                      {isOpen && (day.equipment||[]).flatMap(eq =>
                        (eq.slots||[]).map((slot, si) => (
                          <tr key={`${eq.equipment_name}-${si}`} style={{ background:'#F8FBFF' }}>
                            <td style={{ ...td, paddingLeft:44, color:T.text3, fontSize:11 }}>{slot.start_time}–{slot.end_time}</td>
                            {allEq.map(name => {
                              if (name !== eq.equipment_name) return <td key={name} style={{ ...td, fontSize:11 }}><span style={{ color:'#E2E8F0' }}>·</span></td>;
                              return (
                                <td key={name} style={{ ...td, fontSize:10 }}>
                                  <span style={{ background:`${T.teal}20`, color:T.tealDark, padding:'2px 7px', borderRadius:20, fontWeight:700, fontFamily:T.ff }}>{slot.step_name}</span>
                                  <div style={{ fontSize:9, color:T.text3, marginTop:2 }}>{slot.procedure_name}</div>
                                </td>
                              );
                            })}
                          </tr>
                        ))
                      )}
                    </React.Fragment>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { StaffView, StaffReport, EquipmentReport });
