// ============================================================
// ЛИНИЯ ЖИЗНИ — App Shell
// ============================================================
const { useState, useEffect } = React;

function addDays(dateStr, delta) {
  const d = new Date(dateStr + 'T12:00:00');
  d.setDate(d.getDate() + delta);
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}

function fmtDateLong(dateStr) {
  return new Date(dateStr + 'T12:00:00').toLocaleDateString('ru-RU', { weekday:'long', day:'numeric', month:'long' });
}

/* ── Loading screen ─────────────────────────────────────────── */
function LoadingScreen() {
  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', background:T.bg, gap:16 }}>
      <svg width="44" height="44" viewBox="0 0 44 44" fill="none">
        <rect width="44" height="44" rx="14" fill="rgba(0,191,166,0.12)"/>
        <path d="M7 22 Q12 12 18 22 Q22 29 27 18 Q31 8 37 22" stroke="#00BFA6" strokeWidth="2.5" strokeLinecap="round" fill="none"/>
      </svg>
      <div style={{ fontSize:13, color:T.text3, fontFamily:T.ffBody }}>Загрузка данных…</div>
    </div>
  );
}

/* ── Toast ──────────────────────────────────────────────────── */
function Toast({ msg }) {
  return (
    <div style={{ position:'fixed', bottom:28, left:'50%', transform:'translateX(-50%)', background:T.navy, color:'#fff', padding:'10px 22px', borderRadius:20, fontSize:13, fontWeight:600, fontFamily:T.ff, boxShadow:'0 8px 24px rgba(0,0,0,0.2)', zIndex:2000, pointerEvents:'none' }}>
      ✓ {msg}
    </div>
  );
}

/* ── App ────────────────────────────────────────────────────── */
function App() {
  const [activeTab,     setActiveTab]     = useState(0);
  const [currentDate,   setCurrentDate]   = useState(LL.todayStr());
  const [loading,       setLoading]       = useState(true);
  const [procedures,    setProcedures]    = useState([]);
  const [allProcedures, setAllProcedures] = useState([]);
  const [schedule,      setSchedule]      = useState([]);
  const [toast,         setToast]         = useState('');
  const [showSettings,  setShowSettings]  = useState(false);
  const [isClosed,      setIsClosed]      = useState(false);

  const showToast = msg => {
    setToast(msg);
    setTimeout(() => setToast(''), 3400);
  };

  const loadDay = async (dateStr) => {
    setLoading(true);
    try {
      const data = await LL.loadDayData(dateStr);
      window.PROCEDURE_TYPES = data.procTypes;
      window.EQUIPMENT_LIST  = data.eqList;
      window.STAFF_LIST      = data.staffList;
      window.WORKPLACES      = data.workplaces;
      window.ALL_PROCEDURES  = data.allProcedures;
      setProcedures(data.procedures);
      setSchedule(data.schedule);
      setAllProcedures(data.allProcedures || []);
      setIsClosed(!!data.isClosed);
    } catch (e) {
      showToast('Ошибка загрузки данных');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { loadDay(currentDate); }, [currentDate]);

  const incompleteCount = procedures.filter(p => p.incomplete && !p.cleared).length;
  const partialCount = procedures.filter(p => {
    const pt = (window.PROCEDURE_TYPES||[]).find(t => t.id === p.typeId);
    if (!pt) return false;
    const n = schedule.filter(e => e.procId === p.id).length;
    return n > 0 && n < pt.stages.length;
  }).length;

  const tabs = [
    { label:'ОСНОВ. ДОСКА',  sub:'Оборудование / Время' },
    { label:'ДОСКА',          sub:'Сотрудники / Время' },
    { label:'ОТЧЁТ',          sub:'Загруженность: Сотрудники' },
    { label:'ОТЧЁТ',          sub:'Загруженность: Оборудование' },
  ];

  const isToday = currentDate === LL.todayStr();
  const tomorrowStr = addDays(LL.todayStr(), 1);
  const isTomorrow = currentDate === tomorrowStr;

  const handlePrintCurrent = () => { window.print(); };

  return (
    <div style={{ display:'flex', flexDirection:'column', height:'100vh', background:T.bg, fontFamily:T.ffBody }}>

      {/* ── Header ── */}
      <header className="app-header-no-print" style={{ background:T.navy, color:'#fff', display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 22px', height:54, flexShrink:0, boxShadow:'0 2px 16px rgba(11,37,69,0.3)', zIndex:20 }}>
        <div style={{ display:'flex', alignItems:'center', gap:12 }}>
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <svg width="30" height="30" viewBox="0 0 30 30" fill="none">
              <rect width="30" height="30" rx="9" fill="rgba(0,191,166,0.18)"/>
              <path d="M5 15 Q8 8 12 15 Q15 20 18 12 Q21 5 25 15" stroke="#00BFA6" strokeWidth="2.2" strokeLinecap="round" fill="none"/>
              <circle cx="15" cy="15" r="3" fill="#00BFA6" fillOpacity="0.5"/>
            </svg>
            <div>
              <div style={{ fontWeight:800, fontSize:15, letterSpacing:'-0.04em', lineHeight:1, fontFamily:T.ff, color:'#fff' }}>Линия Жизни</div>
              <div style={{ fontSize:9, color:'rgba(255,255,255,0.4)', letterSpacing:'0.1em', textTransform:'uppercase', marginTop:1 }}>Эмбриология · Лаборатория</div>
            </div>
          </div>
          <div style={{ width:1, height:28, background:'rgba(255,255,255,0.1)', margin:'0 4px' }}></div>
          <div style={{ display:'flex', alignItems:'center', gap:8 }}>
            <button onClick={() => setCurrentDate(d => addDays(d,-1))} style={{ background:'rgba(255,255,255,0.08)', border:'none', color:'rgba(255,255,255,0.7)', width:28, height:28, borderRadius:7, cursor:'pointer', fontSize:16, display:'flex', alignItems:'center', justifyContent:'center' }}>‹</button>
            <input type="date" value={currentDate} onChange={e => e.target.value && setCurrentDate(e.target.value)} style={{ background:'rgba(255,255,255,0.08)', border:'none', color:'rgba(255,255,255,0.85)', fontSize:12, padding:'4px 8px', borderRadius:7, cursor:'pointer', fontFamily:T.ffBody, outline:'none' }} />
            <button onClick={() => setCurrentDate(d => addDays(d,1))} style={{ background:'rgba(255,255,255,0.08)', border:'none', color:'rgba(255,255,255,0.7)', width:28, height:28, borderRadius:7, cursor:'pointer', fontSize:16, display:'flex', alignItems:'center', justifyContent:'center' }}>›</button>
            <button onClick={() => setCurrentDate(LL.todayStr())} style={{ background: isToday ? 'rgba(0,191,166,0.22)' : 'rgba(255,255,255,0.08)', border:'none', color: isToday ? '#5EEAD4' : 'rgba(255,255,255,0.65)', fontSize:11, padding:'4px 10px', borderRadius:7, cursor:'pointer', fontFamily:T.ff, fontWeight:600 }}>Сегодня</button>
            <button onClick={() => setCurrentDate(tomorrowStr)} style={{ background: isTomorrow ? 'rgba(0,191,166,0.22)' : 'rgba(255,255,255,0.08)', border:'none', color: isTomorrow ? '#5EEAD4' : 'rgba(255,255,255,0.65)', fontSize:11, padding:'4px 10px', borderRadius:7, cursor:'pointer', fontFamily:T.ff, fontWeight:600 }}>Завтра</button>
            <span style={{ fontSize:12, color:'rgba(255,255,255,0.55)', fontFamily:T.ffBody, textTransform:'capitalize' }}>{fmtDateLong(currentDate)}</span>
          </div>
        </div>

        <div style={{ display:'flex', alignItems:'center', gap:10 }}>
          {incompleteCount > 0 && (
            <div style={{ display:'flex', alignItems:'center', gap:6, background:'rgba(239,68,68,0.16)', border:'1px solid rgba(239,68,68,0.3)', borderRadius:20, padding:'4px 12px' }}>
              <div style={{ width:6, height:6, borderRadius:3, background:'#EF4444' }}></div>
              <span style={{ fontSize:11, color:'#FCA5A5', fontWeight:700, fontFamily:T.ff }}>{incompleteCount} неполных</span>
            </div>
          )}
          {partialCount > 0 && (
            <div style={{ display:'flex', alignItems:'center', gap:6, background:'rgba(245,158,11,0.16)', border:'1px solid rgba(245,158,11,0.3)', borderRadius:20, padding:'4px 12px' }}>
              <div style={{ width:6, height:6, borderRadius:3, background:'#F59E0B' }}></div>
              <span style={{ fontSize:11, color:'#FDE68A', fontWeight:700, fontFamily:T.ff }}>{partialCount} частичных</span>
            </div>
          )}
          <button onClick={handlePrintCurrent} title="Печать" style={{ background:'rgba(255,255,255,0.08)', border:'1px solid rgba(255,255,255,0.15)', borderRadius:20, padding:'5px 14px', cursor:'pointer', display:'flex', alignItems:'center', gap:6, color:'rgba(255,255,255,0.75)', fontSize:12, fontWeight:600, fontFamily:T.ff }}>
            <span style={{ fontSize:14 }}>🖨</span> Печать
          </button>
          <button onClick={() => setShowSettings(true)} style={{ background:'rgba(255,255,255,0.08)', border:'1px solid rgba(255,255,255,0.15)', borderRadius:20, padding:'5px 14px', cursor:'pointer', display:'flex', alignItems:'center', gap:6, color:'rgba(255,255,255,0.75)', fontSize:12, fontWeight:600, fontFamily:T.ff }}>
            <span style={{ fontSize:14 }}>⚙</span> Справочники
          </button>
          <div style={{ display:'flex', alignItems:'center', gap:8, background:'rgba(255,255,255,0.08)', borderRadius:20, padding:'5px 12px' }}>
            <div style={{ width:26, height:26, borderRadius:13, background:T.teal, display:'flex', alignItems:'center', justifyContent:'center', fontSize:10, fontWeight:800, color:'#fff', fontFamily:T.ff }}>ЗЛ</div>
            <span style={{ fontSize:12, color:'rgba(255,255,255,0.82)', fontWeight:500, fontFamily:T.ffBody }}>Зав. лабораторией</span>
          </div>
        </div>
      </header>

      <div className="tabs-no-print" style={{ background:'#fff', borderBottom:`1.5px solid ${T.border}`, display:'flex', alignItems:'stretch', padding:'0 22px', flexShrink:0, zIndex:15 }}>
        {tabs.map((tab, i) => {
          const active = activeTab === i;
          return (
            <button key={i} onClick={() => setActiveTab(i)} style={{ border:'none', background:'none', cursor:'pointer', padding:'0 18px', display:'flex', flexDirection:'column', justifyContent:'center', alignItems:'flex-start', height:50, fontFamily:'inherit', position:'relative', borderBottom:active?`2.5px solid ${T.navy}`:'2.5px solid transparent', marginBottom:-1.5 }}>
              <span style={{ fontSize:11, fontWeight:800, letterSpacing:'0.06em', color:active?T.navy:T.text3, textTransform:'uppercase', lineHeight:1, fontFamily:T.ff }}>{tab.label}</span>
              <span style={{ fontSize:11, fontWeight:400, color:active?T.text2:T.border, marginTop:2, whiteSpace:'nowrap', fontFamily:T.ffBody }}>{tab.sub}</span>
            </button>
          );
        })}
      </div>

      <div style={{ flex:1, overflow:'hidden', display:'flex', flexDirection:'column' }} className="content-print">
        {loading ? <LoadingScreen /> : (
          <>
            {activeTab === 0 && (
              <div style={{ flex:1, overflow:'hidden', display:'flex' }}>
                <BoardView procedures={procedures} setProcedures={setProcedures}
                  schedule={schedule} setSchedule={setSchedule}
                  allProcedures={allProcedures} setAllProcedures={setAllProcedures}
                  isClosed={isClosed} setIsClosed={setIsClosed}
                  currentDate={currentDate} showToast={showToast} />
              </div>
            )}
            {activeTab === 1 && (
              <div style={{ flex:1, overflow:'hidden', display:'flex' }}>
                <StaffView schedule={schedule} procedures={procedures} />
              </div>
            )}
            {activeTab === 2 && (
              <div style={{ flex:1, overflow:'hidden', display:'flex' }}>
                <StaffReport />
              </div>
            )}
            {activeTab === 3 && (
              <div style={{ flex:1, overflow:'hidden', display:'flex' }}>
                <EquipmentReport />
              </div>
            )}
          </>
        )}
      </div>

      {toast && <Toast msg={toast} />}
      {showSettings && (
        <SettingsModal onClose={() => setShowSettings(false)} onReload={() => loadDay(currentDate)} />
      )}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
