// ───── Kalendár a dovolenky — tímový zdieľaný kalendár + approval workflow ─────

const LEAVE_TYPES = [
  { id: 'vacation',         label: 'Dovolenka',       color: '#f3a712', icon: '🏖', needsPaper: false },
  { id: 'sick',             label: 'PN',              color: '#d64545', icon: '🤒', needsPaper: true  },
  { id: 'doctor',           label: 'Lekár',           color: '#7b68ee', icon: '⚕️', needsPaper: true  },
  { id: 'doctor_accompany', label: 'Lekár — sprievod',color: '#c084fc', icon: '👥', needsPaper: true  },
  { id: 'personal',         label: 'Osobné voľno',    color: '#2a9d5f', icon: '📋', needsPaper: false },
  { id: 'home_office',      label: 'Home office',     color: '#3a6da0', icon: '🏠', needsPaper: false },
  { id: 'business_trip',    label: 'Služobná cesta',  color: '#8a5a2b', icon: '✈️', needsPaper: false },
  { id: 'training',         label: 'Školenie',        color: '#16a34a', icon: '🎓', needsPaper: false },
  { id: 'other',            label: 'Iné',             color: '#64748b', icon: '•',  needsPaper: false },
];
function leaveTypeMeta(id) { return LEAVE_TYPES.find(t => t.id === id) || LEAVE_TYPES[LEAVE_TYPES.length - 1]; }

function pad2(n) { return String(n).padStart(2, '0'); }
function isoFromDate(d) { return `${d.getFullYear()}-${pad2(d.getMonth()+1)}-${pad2(d.getDate())}`; }
function parseIso(s) { const [y, m, d] = s.split('-').map(Number); return new Date(y, m-1, d); }
function initialsOf(name) { return (name || '?').split(/\s+/).map(p => p[0]).filter(Boolean).join('').slice(0, 2).toUpperCase(); }

// Build 42 cells (6 weeks) starting on Monday that contains the 1st of the month.
function buildMonthGrid(year, month) {
  const first = new Date(year, month, 1);
  const dow = (first.getDay() + 6) % 7; // 0 = Mon
  const start = new Date(year, month, 1 - dow);
  const cells = [];
  for (let i = 0; i < 42; i++) {
    const d = new Date(start); d.setDate(start.getDate() + i);
    cells.push({
      iso: isoFromDate(d),
      date: d,
      inMonth: d.getMonth() === month,
    });
  }
  return cells;
}

// Does a leave [start..end] overlap a single day iso?
function leaveCoversDay(leave, iso) {
  return iso >= leave.start_date && iso <= leave.end_date;
}

function CalendarLeave() {
  const now = new Date();
  const [view, setView] = React.useState({ year: now.getFullYear(), month: now.getMonth() });
  const [leaves, setLeaves]   = React.useState([]);
  const [myLeaves, setMyLeaves] = React.useState([]);
  const [pending, setPending] = React.useState([]);
  const [myAllowance, setMyAllowance] = React.useState(null);
  const [allAllowances, setAllAllowances] = React.useState([]);
  const [editAllowance, setEditAllowance] = React.useState(null); // { user, data }
  const [loading, setLoading] = React.useState(true);
  const [toast, setToast]     = React.useState(null);
  const [dayModal, setDayModal] = React.useState(null);   // iso
  const [newModal, setNewModal] = React.useState(false);
  const [filterMine, setFilterMine] = React.useState(false);

  const user = (window.currentSession && window.currentSession.user) || {};
  const canApprove = window.hasPerm ? window.hasPerm('calendar.edit') : false;

  const monthCells = React.useMemo(() => buildMonthGrid(view.year, view.month), [view]);
  const monthStart = monthCells[0].iso;
  const monthEnd   = monthCells[monthCells.length - 1].iso;

  async function reload() {
    setLoading(true);
    const qs = `?from=${monthStart}&to=${monthEnd}`;
    const [r1, r2, r4] = await Promise.all([
      fetch('/api/leaves' + qs, { credentials: 'same-origin' }).then(r => r.json()),
      fetch('/api/leaves/my', { credentials: 'same-origin' }).then(r => r.json()),
      fetch(`/api/leaves/allowances/${user.id}?year=${view.year}`, { credentials: 'same-origin' }).then(r => r.json()),
    ]);
    if (r1?.ok) setLeaves(r1.leaves || []);
    if (r2?.ok) setMyLeaves(r2.leaves || []);
    if (r4?.ok) setMyAllowance(r4);
    if (canApprove) {
      const [r3, r5] = await Promise.all([
        fetch('/api/leaves/pending', { credentials: 'same-origin' }).then(r => r.json()),
        fetch(`/api/leaves/allowances?year=${view.year}`, { credentials: 'same-origin' }).then(r => r.json()),
      ]);
      if (r3?.ok) setPending(r3.leaves || []);
      if (r5?.ok) setAllAllowances(r5.allowances || []);
    }
    setLoading(false);
  }
  React.useEffect(() => { reload(); /* eslint-disable-next-line */ }, [view.year, view.month]);

  const monthNames = ['Január','Február','Marec','Apríl','Máj','Jún','Júl','August','September','Október','November','December'];
  const dayNames = ['Po','Ut','St','Št','Pi','So','Ne'];
  const todayIso = isoFromDate(new Date());

  function prevMonth() { setView(v => v.month === 0 ? { year: v.year - 1, month: 11 } : { year: v.year, month: v.month - 1 }); }
  function nextMonth() { setView(v => v.month === 11 ? { year: v.year + 1, month: 0 } : { year: v.year, month: v.month + 1 }); }
  function goToday()   { setView({ year: now.getFullYear(), month: now.getMonth() }); }

  // Filter based on "Moje" toggle
  const visibleLeaves = React.useMemo(() => {
    return filterMine ? leaves.filter(l => l.user_id === user.id) : leaves;
  }, [leaves, filterMine, user.id]);

  // Approve / reject
  async function act(leave, kind) {
    const note = kind === 'reject' ? (prompt('Dôvod zamietnutia (voliteľne):') || '') : '';
    const r = await fetch(`/api/leaves/${leave.id}/${kind}`, {
      method: 'POST', credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ note }),
    });
    if (r.ok) { setToast({ kind: 'success', text: kind === 'approve' ? 'Schválené.' : 'Zamietnuté.' }); reload(); }
    else setToast({ kind: 'error', text: 'Chyba.' });
  }
  async function cancelMine(leave) {
    if (!confirm('Zrušiť túto žiadosť?')) return;
    const r = await fetch(`/api/leaves/${leave.id}/cancel`, { method: 'PATCH', credentials: 'same-origin' });
    if (r.ok) { setToast({ kind: 'success', text: 'Zrušené.' }); reload(); }
  }

  return (
    <AppShell active="calendar" crumbs={['ERP','Kalendár a dovolenky']}>
      {toast && <Toast kind={toast.kind} onClose={() => setToast(null)}>{toast.text}</Toast>}
      {dayModal && (
        <DayDetailModal
          iso={dayModal}
          leaves={leaves.filter(l => leaveCoversDay(l, dayModal))}
          currentUserId={user.id}
          canApprove={canApprove}
          onClose={() => setDayModal(null)}
          onAction={act}
          onCancelMine={cancelMine}
        />
      )}
      {newModal && (
        <NewLeaveModal
          onClose={() => setNewModal(false)}
          onSubmitted={(resp) => {
            setNewModal(false);
            setToast({ kind: 'success', text: resp.status === 'pending' ? 'Žiadosť odoslaná administrátorovi.' : 'Uložené.' });
            reload();
          }}
        />
      )}

      <div className="page-head">
        <div>
          <h1>Tímový kalendár</h1>
          <p>Zdieľaný prehľad · dovolenky, PN, home office, školenia · {leaves.length} udalostí v tomto mesiaci</p>
        </div>
        <div className="page-head-actions">
          <button className="btn" onClick={reload}><Ico.refresh/>Obnoviť</button>
          <button className="btn btn-amber" onClick={() => setNewModal(true)}><Ico.plus/>Žiadosť o voľno</button>
        </div>
      </div>

      <div className="cal-layout">
        {/* Main calendar */}
        <div className="card">
          <div className="card-head cal-head">
            <div className="hstack cal-nav">
              <button className="btn btn-sm" onClick={prevMonth}>←</button>
              <b style={{minWidth:140, textAlign:'center'}}>{monthNames[view.month]} {view.year}</b>
              <button className="btn btn-sm" onClick={nextMonth}>→</button>
              <button className="btn btn-sm" onClick={goToday}>Dnes</button>
            </div>
            <div className="hstack" style={{gap:6, flexWrap:'wrap'}}>
              <div className="seg">
                <button className={!filterMine ? 'active' : ''} onClick={() => setFilterMine(false)}>Celý tím</button>
                <button className={filterMine ? 'active' : ''} onClick={() => setFilterMine(true)}>Moje</button>
              </div>
            </div>
          </div>

          <div className="cal-grid-wrap">
            <div className="cal-weekday-row">
              {dayNames.map(d => <div key={d} className="cal-weekday">{d}</div>)}
            </div>
            <div className="cal-grid">
              {monthCells.map((c, idx) => {
                const dayLeaves = visibleLeaves.filter(l => leaveCoversDay(l, c.iso));
                const isToday = c.iso === todayIso;
                return (
                  <button
                    key={idx}
                    className={`cal-cell${c.inMonth ? '' : ' out-month'}${isToday ? ' is-today' : ''}`}
                    onClick={() => setDayModal(c.iso)}
                  >
                    <span className="cal-daynum">{c.date.getDate()}</span>
                    <div className="cal-events">
                      {dayLeaves.slice(0, 3).map(l => {
                        const meta = leaveTypeMeta(l.leave_type);
                        return (
                          <div
                            key={l.id}
                            className={`cal-event${l.status === 'pending' ? ' pending' : ''}`}
                            style={{'--ev-color': meta.color}}
                            title={`${l.user_name} · ${meta.label}${l.status === 'pending' ? ' · čaká na schválenie' : ''}`}
                          >
                            <span className="cal-event-name">{initialsOf(l.user_name)} · {meta.label}</span>
                          </div>
                        );
                      })}
                      {dayLeaves.length > 3 && <span className="cal-event-more">+{dayLeaves.length - 3} ďalších</span>}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          <div className="cal-legend">
            {LEAVE_TYPES.map(t => (
              <span key={t.id} className="cal-legend-item">
                <span className="cal-legend-swatch" style={{background:t.color}}/>
                {t.label}
              </span>
            ))}
          </div>
        </div>

        {/* Side panel: my leaves + approvals */}
        <div className="vstack" style={{gap:14}}>
          {/* My remaining allowance for the current year */}
          {myAllowance && (
            <div className="card">
              <div className="card-head">
                <h3>Môj zostatok · {view.year}</h3>
                {canApprove && <button className="btn btn-xs" style={{marginLeft:'auto'}} onClick={() => setEditAllowance({ userId: user.id, userName: user.name, data: myAllowance })}>Upraviť</button>}
              </div>
              <div className="cal-allowance-grid">
                <AllowanceTile color="#f3a712" icon="🏖"  label="Dovolenka"        used={myAllowance.used.vacation}         total={myAllowance.vacation_total}/>
                <AllowanceTile color="#7b68ee" icon="⚕️"  label="Lekár"            used={myAllowance.used.doctor}           total={myAllowance.doctor_total}/>
                <AllowanceTile color="#c084fc" icon="👥"  label="Sprievod"         used={myAllowance.used.doctor_accompany} total={myAllowance.doctor_accompany_total}/>
                {myAllowance.personal_total > 0 && (
                  <AllowanceTile color="#2a9d5f" icon="📋" label="Osobné voľno"    used={myAllowance.used.personal}         total={myAllowance.personal_total}/>
                )}
              </div>
            </div>
          )}

          <div className="card">
            <div className="card-head"><h3>Moje žiadosti ({myLeaves.length})</h3></div>
            {myLeaves.length === 0 ? (
              <div className="muted" style={{padding:20, textAlign:'center'}}>Zatiaľ žiadne.</div>
            ) : (
              <div className="vstack" style={{gap:0}}>
                {myLeaves.slice(0, 8).map(l => <MyLeaveRow key={l.id} leave={l} onCancel={cancelMine} onReload={reload} canUpload={true}/>)}
              </div>
            )}
          </div>

          {canApprove && (
            <div className="card">
              <div className="card-head">
                <h3>Na schválenie {pending.length > 0 && <span className="chip amber dot">{pending.length}</span>}</h3>
              </div>
              {pending.length === 0 ? (
                <div className="muted" style={{padding:20, textAlign:'center'}}>Žiadne nové žiadosti.</div>
              ) : (
                <div className="vstack" style={{gap:0}}>
                  {pending.map(l => <PendingLeaveRow key={l.id} leave={l} onAction={act} onReload={reload}/>)}
                </div>
              )}
            </div>
          )}

          {canApprove && (
            <div className="card">
              <div className="card-head">
                <h3>Tím · zostatky {view.year}</h3>
              </div>
              <div className="ai-table-wrap">
                <table className="tbl">
                  <thead><tr><th>Používateľ</th><th>Dovolenka</th><th>Lekár</th><th>Sprievod</th><th></th></tr></thead>
                  <tbody>
                    {allAllowances.map(a => (
                      <tr key={a.user_id}>
                        <td><b>{a.user.name}</b><div className="small muted">{a.user.role}</div></td>
                        <td>{a.used.vacation} / {a.vacation_total}</td>
                        <td>{a.used.doctor} / {a.doctor_total}</td>
                        <td>{a.used.doctor_accompany} / {a.doctor_accompany_total}</td>
                        <td><button className="btn btn-xs" onClick={() => setEditAllowance({ userId: a.user_id, userName: a.user.name, data: a })}>Upraviť</button></td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>

        {editAllowance && (
          <EditAllowanceModal
            userId={editAllowance.userId}
            userName={editAllowance.userName}
            year={view.year}
            initial={editAllowance.data}
            canEdit={canApprove}
            onClose={() => setEditAllowance(null)}
            onSaved={() => { setEditAllowance(null); setToast({ kind:'success', text:'Nároky uložené.' }); reload(); }}
          />
        )}
      </div>

      {loading && <div className="small muted" style={{padding:10, textAlign:'center'}}>Načítavam…</div>}
    </AppShell>
  );
}

function AllowanceTile({ color, icon, label, used, total }) {
  const pct = total > 0 ? Math.min(100, Math.round((used / total) * 100)) : 0;
  const remaining = Math.max(0, (total || 0) - (used || 0));
  return (
    <div className="cal-allowance-tile">
      <div className="hstack" style={{gap:8}}>
        <span className="cal-type-swatch" style={{background:color, width:28, height:28, fontSize:13}}>{icon}</span>
        <div style={{flex:1, minWidth:0}}>
          <div className="small muted" style={{fontSize:10.5, textTransform:'uppercase', letterSpacing:'0.06em'}}>{label}</div>
          <div style={{fontSize:15, fontWeight:700, color:'var(--ink-900)'}}>
            {remaining} <span className="small muted" style={{fontWeight:400, fontSize:11}}>z {total}</span>
          </div>
        </div>
      </div>
      <div className="cal-allowance-bar"><span style={{width: pct + '%', background: color}}/></div>
    </div>
  );
}

function EditAllowanceModal({ userId, userName, year, initial, canEdit, onClose, onSaved }) {
  const [data, setData] = React.useState({
    vacation_total: initial.vacation_total,
    doctor_total: initial.doctor_total,
    doctor_accompany_total: initial.doctor_accompany_total,
    personal_total: initial.personal_total,
    note: initial.note || '',
  });
  const [busy, setBusy] = React.useState(false);
  const set = (k, v) => setData(p => ({ ...p, [k]: v }));

  async function save() {
    if (!canEdit) return;
    setBusy(true);
    const r = await fetch(`/api/leaves/allowances/${userId}?year=${year}`, {
      method: 'PATCH', credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    setBusy(false);
    if (r.ok) onSaved();
  }

  return (
    <Modal title={`Nároky · ${userName} · ${year}`} width={480} onClose={onClose}
           footer={<>
             <button className="btn" onClick={onClose}>Zavrieť</button>
             {canEdit && <button className="btn btn-primary btn-sm" onClick={save} disabled={busy}>{busy ? 'Ukladám…' : 'Uložiť'}</button>}
           </>}>
      {!canEdit && <div className="small muted" style={{marginBottom:10}}>Nároky môže meniť len administrátor.</div>}
      <div className="vstack" style={{gap:10}}>
        <div className="hstack" style={{gap:10}}>
          <div className="field" style={{flex:1, minWidth:0}}><label>🏖 Dovolenka (dní/rok)</label>
            <input type="number" min={0} step="0.5" className="input" value={data.vacation_total} onChange={e => set('vacation_total', e.target.value)} disabled={!canEdit}/>
            <div className="small muted">Využité: {initial.used.vacation}</div>
          </div>
          <div className="field" style={{flex:1, minWidth:0}}><label>📋 Osobné voľno</label>
            <input type="number" min={0} step="0.5" className="input" value={data.personal_total} onChange={e => set('personal_total', e.target.value)} disabled={!canEdit}/>
            <div className="small muted">Využité: {initial.used.personal}</div>
          </div>
        </div>
        <div className="hstack" style={{gap:10}}>
          <div className="field" style={{flex:1, minWidth:0}}><label>⚕️ Lekár</label>
            <input type="number" min={0} step="0.5" className="input" value={data.doctor_total} onChange={e => set('doctor_total', e.target.value)} disabled={!canEdit}/>
            <div className="small muted">Využité: {initial.used.doctor}</div>
          </div>
          <div className="field" style={{flex:1, minWidth:0}}><label>👥 Sprievod k lekárovi</label>
            <input type="number" min={0} step="0.5" className="input" value={data.doctor_accompany_total} onChange={e => set('doctor_accompany_total', e.target.value)} disabled={!canEdit}/>
            <div className="small muted">Využité: {initial.used.doctor_accompany}</div>
          </div>
        </div>
        <div className="field">
          <label>Poznámka (voliteľné)</label>
          <textarea className="input" rows={2} value={data.note} onChange={e => set('note', e.target.value)} disabled={!canEdit}/>
        </div>
      </div>
    </Modal>
  );
}

function MyLeaveRow({ leave, onCancel, onReload, canUpload = false }) {
  const meta = leaveTypeMeta(leave.leave_type);
  const [showAttach, setShowAttach] = React.useState(false);
  const statusChip =
    leave.status === 'approved' ? <span className="chip green dot">Schválené</span> :
    leave.status === 'pending'  ? <span className="chip amber dot">Čaká</span> :
    leave.status === 'rejected' ? <span className="chip red dot">Zamietnuté</span> :
                                   <span className="chip gray dot">Zrušené</span>;
  const isActive = leave.status === 'pending' || leave.status === 'approved';
  return (
    <div className="cal-side-row">
      <div className="hstack" style={{alignItems:'flex-start', gap:8}}>
        <span className="cal-type-swatch" style={{background:meta.color}}>{meta.icon}</span>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontWeight:500, fontSize:12.5}}>{meta.label}</div>
          <div className="small muted">{leave.start_date === leave.end_date ? leave.start_date : `${leave.start_date} → ${leave.end_date}`}{leave.days_count ? ` · ${leave.days_count} dní` : ''}</div>
        </div>
        {statusChip}
      </div>
      {leave.reason && <div className="small muted" style={{marginTop:3}}>„{leave.reason}"</div>}
      {leave.review_note && <div className="small muted" style={{marginTop:2, fontStyle:'italic'}}>Poznámka: {leave.review_note}</div>}

      <div className="hstack" style={{marginTop:6, gap:6, flexWrap:'wrap'}}>
        <button className="btn btn-xs" onClick={() => setShowAttach(s => !s)}>
          📎 Priepustky {leave.attachments_count > 0 && `(${leave.attachments_count})`}
        </button>
        {isActive && <button className="btn btn-xs btn-danger" style={{marginLeft:'auto'}} onClick={() => onCancel(leave)}>Zrušiť</button>}
      </div>
      {showAttach && <AttachmentsPanel leave={leave} canUpload={canUpload && isActive} onChange={onReload}/>}
    </div>
  );
}

// Shared panel — list + upload of attachments for a single leave record.
function AttachmentsPanel({ leave, canUpload, onChange }) {
  const [list, setList] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [uploading, setUploading] = React.useState(false);

  async function reload() {
    setLoading(true);
    const r = await fetch(`/api/leaves/${leave.id}/attachments`, { credentials: 'same-origin' });
    const j = await r.json().catch(() => ({}));
    setLoading(false);
    if (j?.ok) setList(j.attachments || []);
  }
  React.useEffect(() => { reload(); /* eslint-disable-next-line */ }, [leave.id]);

  async function upload(file) {
    if (!file) return;
    setUploading(true);
    const fd = new FormData();
    fd.append('file', file);
    const r = await fetch(`/api/leaves/${leave.id}/attachments`, { method: 'POST', credentials: 'same-origin', body: fd });
    setUploading(false);
    if (r.ok) { reload(); onChange && onChange(); }
    else { const j = await r.json().catch(() => ({})); alert(j.message || 'Upload zlyhal.'); }
  }

  async function del(a) {
    if (!confirm('Zmazať prílohu?')) return;
    const r = await fetch(`/api/leaves/${leave.id}/attachments/${a.id}`, { method: 'DELETE', credentials: 'same-origin' });
    if (r.ok) { reload(); onChange && onChange(); }
  }

  return (
    <div className="cal-attach-panel">
      {loading ? <div className="small muted" style={{padding:6}}>Načítavam…</div> :
       list.length === 0 ? <div className="small muted" style={{padding:6}}>Žiadne priepustky / paragrafy.</div> :
       <div className="vstack" style={{gap:4}}>
        {list.map(a => (
          <div key={a.id} className="cal-attach-row">
            <a href={a.url} target="_blank" rel="noreferrer" className="cal-attach-link">
              {a.mime_type?.startsWith('image/')
                ? <img src={a.url} alt={a.file_name} className="cal-attach-thumb"/>
                : <span className="cal-attach-icon">📄</span>}
              <span className="cal-attach-name">{a.file_name}</span>
            </a>
            <div className="small muted">{Math.round((a.size_bytes||0)/1024)} kB</div>
            {canUpload && <button className="btn btn-xs btn-danger" onClick={() => del(a)}><Ico.x/></button>}
          </div>
        ))}
       </div>}
      {canUpload && (
        <label className="btn btn-xs" style={{marginTop:6, cursor:'pointer', alignSelf:'flex-start'}}>
          <Ico.upload/>{uploading ? 'Nahrávam…' : 'Pridať prílohu'}
          <input type="file" accept="image/*,application/pdf" hidden onChange={e => upload(e.target.files?.[0])}/>
        </label>
      )}
    </div>
  );
}

function PendingLeaveRow({ leave, onAction, onReload }) {
  const meta = leaveTypeMeta(leave.leave_type);
  const [showAttach, setShowAttach] = React.useState(false);
  return (
    <div className="cal-side-row">
      <div className="hstack" style={{alignItems:'flex-start'}}>
        <div className="sb-avatar" style={{background:'var(--navy-600)', color:'#fff', width:28, height:28, fontSize:10, flexShrink:0}}>{initialsOf(leave.user_name)}</div>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontWeight:500, fontSize:12.5}}>{leave.user_name}</div>
          <div className="small muted" style={{display:'flex', alignItems:'center', gap:6, flexWrap:'wrap'}}>
            <span style={{color:meta.color, fontWeight:600}}>{meta.icon} {meta.label}</span> ·
            {leave.start_date === leave.end_date ? leave.start_date : `${leave.start_date} → ${leave.end_date}`}
            {leave.days_count ? ` · ${leave.days_count} dní` : ''}
          </div>
          {leave.reason && <div className="small muted" style={{marginTop:3, fontStyle:'italic'}}>„{leave.reason}"</div>}
        </div>
      </div>
      <div className="hstack" style={{gap:6, marginTop:6, flexWrap:'wrap'}}>
        <button className="btn btn-xs" onClick={() => setShowAttach(s => !s)}>
          📎 {leave.attachments_count > 0 ? `${leave.attachments_count} priepustky` : 'Žiadne priepustky'}
        </button>
        <div style={{marginLeft:'auto', display:'flex', gap:6}}>
          <button className="btn btn-xs btn-danger" onClick={() => onAction(leave, 'reject')}><Ico.x/>Zamietnuť</button>
          <button className="btn btn-xs" style={{background:'var(--green-100)', color:'#135e37', borderColor:'transparent'}} onClick={() => onAction(leave, 'approve')}>
            <Ico.check/>Schváliť
          </button>
        </div>
      </div>
      {showAttach && <AttachmentsPanel leave={leave} canUpload={true} onChange={onReload}/>}
    </div>
  );
}

function DayDetailModal({ iso, leaves, currentUserId, canApprove, onClose, onAction, onCancelMine }) {
  const d = parseIso(iso);
  const label = d.toLocaleDateString('sk-SK', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
  return (
    <Modal title={label} width={520} onClose={onClose}
           footer={<button className="btn" onClick={onClose}>Zavrieť</button>}>
      {leaves.length === 0 ? (
        <div className="muted" style={{padding:14, textAlign:'center'}}>V tento deň nemá nikto plánované voľno.</div>
      ) : (
        <div className="vstack" style={{gap:8}}>
          {leaves.map(l => {
            const meta = leaveTypeMeta(l.leave_type);
            const isMine = l.user_id === currentUserId;
            return (
              <div key={l.id} className="card" style={{padding:10}}>
                <div className="hstack" style={{alignItems:'flex-start'}}>
                  <div className="sb-avatar" style={{background:meta.color, color:'#fff', width:32, height:32, fontSize:11, flexShrink:0}}>{initialsOf(l.user_name)}</div>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{fontWeight:500}}>{l.user_name} <span className="small muted">· {l.user_role}</span></div>
                    <div className="small muted">
                      <span style={{color:meta.color, fontWeight:600}}>{meta.icon} {meta.label}</span>
                      {' · '}{l.start_date === l.end_date ? l.start_date : `${l.start_date} → ${l.end_date}`}
                      {l.days_count ? ` · ${l.days_count} dní` : ''}
                    </div>
                    {l.reason && <div className="small muted" style={{marginTop:3, fontStyle:'italic'}}>„{l.reason}"</div>}
                  </div>
                  {l.status === 'pending' && <span className="chip amber dot" style={{flexShrink:0}}>Čaká</span>}
                  {l.status === 'approved' && <span className="chip green dot" style={{flexShrink:0}}>Schválené</span>}
                </div>
                {/* Attachments — admin can always see; owner can upload to own */}
                {(canApprove || isMine) && <DayLeaveAttachments leave={l} canUpload={isMine && (l.status === 'pending' || l.status === 'approved')}/>}
                <div className="hstack" style={{gap:6, marginTop:8, justifyContent:'flex-end', flexWrap:'wrap'}}>
                  {canApprove && l.status === 'pending' && <>
                    <button className="btn btn-xs btn-danger" onClick={() => onAction(l, 'reject')}>Zamietnuť</button>
                    <button className="btn btn-xs" style={{background:'var(--green-100)', color:'#135e37', borderColor:'transparent'}} onClick={() => onAction(l, 'approve')}>Schváliť</button>
                  </>}
                  {isMine && (l.status === 'pending' || l.status === 'approved') && (
                    <button className="btn btn-xs btn-danger" onClick={() => onCancelMine(l)}>Zrušiť moju žiadosť</button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </Modal>
  );
}

function DayLeaveAttachments({ leave, canUpload }) {
  const [show, setShow] = React.useState(leave.attachments_count > 0);
  if (!show) {
    return (
      <button className="btn btn-xs" style={{marginTop:6}} onClick={() => setShow(true)}>
        📎 {leave.attachments_count > 0 ? `${leave.attachments_count} priepustky` : 'Pridať priepustku'}
      </button>
    );
  }
  return <AttachmentsPanel leave={leave} canUpload={canUpload}/>;
}

function NewLeaveModal({ onClose, onSubmitted }) {
  const [type, setType] = React.useState('vacation');
  const [from, setFrom] = React.useState(isoFromDate(new Date()));
  const [to, setTo]     = React.useState(isoFromDate(new Date()));
  const [reason, setReason] = React.useState('');
  const [files, setFiles] = React.useState([]);   // File[] to upload after create
  const [busy, setBusy] = React.useState(false);
  const [err, setErr]   = React.useState('');
  const [allowance, setAllowance] = React.useState(null);

  const user = (window.currentSession && window.currentSession.user) || {};
  const typeMeta = leaveTypeMeta(type);

  React.useEffect(() => {
    fetch(`/api/leaves/allowances/${user.id}?year=${new Date().getFullYear()}`, { credentials: 'same-origin' })
      .then(r => r.json()).then(j => { if (j?.ok) setAllowance(j); });
  }, [user.id]);

  // Keep "to" >= "from"
  React.useEffect(() => { if (to < from) setTo(from); }, [from]);     // eslint-disable-line

  // Rough working-day preview
  const days = React.useMemo(() => {
    const a = parseIso(from), b = parseIso(to);
    if (b < a) return 0;
    let n = 0;
    for (const d = new Date(a); d <= b; d.setDate(d.getDate()+1)) {
      const dow = d.getDay();
      if (dow !== 0 && dow !== 6) n++;
    }
    return n;
  }, [from, to]);

  async function submit(e) {
    e.preventDefault();
    setBusy(true); setErr('');
    const r = await fetch('/api/leaves', {
      method: 'POST', credentials: 'same-origin',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ leave_type: type, start_date: from, end_date: to, reason: reason.trim() || null }),
    });
    const j = await r.json().catch(() => ({}));
    if (!r.ok || !j.ok) { setBusy(false); setErr(j.error || 'Chyba.'); return; }

    // Upload attached files to the newly created leave (best-effort)
    if (files.length > 0) {
      for (const f of files) {
        const fd = new FormData(); fd.append('file', f);
        try { await fetch(`/api/leaves/${j.id}/attachments`, { method: 'POST', credentials: 'same-origin', body: fd }); } catch {}
      }
    }
    setBusy(false);
    onSubmitted(j);
  }

  function remainingFor(typeId) {
    if (!allowance) return null;
    if (typeId === 'vacation')         return { remaining: allowance.remaining.vacation,         total: allowance.vacation_total };
    if (typeId === 'doctor')           return { remaining: allowance.remaining.doctor,           total: allowance.doctor_total };
    if (typeId === 'doctor_accompany') return { remaining: allowance.remaining.doctor_accompany, total: allowance.doctor_accompany_total };
    if (typeId === 'personal' && allowance.personal_total > 0) return { remaining: allowance.remaining.personal, total: allowance.personal_total };
    return null;
  }
  const rem = remainingFor(type);

  return (
    <Modal title="Nová žiadosť o voľno" width={480} onClose={onClose}
           footer={<>
             <button className="btn" onClick={onClose}>Zavrieť</button>
             <button className="btn btn-primary btn-sm" onClick={submit} disabled={busy || !from || !to}>
               {busy ? 'Odosielam…' : 'Odoslať'}
             </button>
           </>}>
      <form onSubmit={submit} className="vstack" style={{gap:10}}>
        <div className="field">
          <label>Typ</label>
          <div className="cal-type-grid">
            {LEAVE_TYPES.map(t => (
              <button key={t.id} type="button"
                className={`cal-type-btn${type === t.id ? ' is-active' : ''}`}
                style={{'--type-color': t.color}}
                onClick={() => setType(t.id)}>
                <span className="cal-type-btn-icon">{t.icon}</span>
                <span>{t.label}</span>
              </button>
            ))}
          </div>
        </div>
        <div className="hstack" style={{gap:10}}>
          <div className="field" style={{flex:1, minWidth:0}}>
            <label>Od</label>
            <input type="date" className="input" value={from} onChange={e => setFrom(e.target.value)} required/>
          </div>
          <div className="field" style={{flex:1, minWidth:0}}>
            <label>Do</label>
            <input type="date" className="input" value={to} min={from} onChange={e => setTo(e.target.value)} required/>
          </div>
        </div>
        <div className="field">
          <label>Dôvod (voliteľné)</label>
          <textarea className="input" rows={3} value={reason} onChange={e => setReason(e.target.value)} placeholder="napr. rodinná dovolenka"/>
        </div>

        {typeMeta.needsPaper && (
          <div className="field">
            <label>📎 Priepustka / paragraf (voliteľné)</label>
            <div className="cal-file-drop">
              <input
                type="file" multiple accept="image/*,application/pdf"
                onChange={e => setFiles(Array.from(e.target.files || []))}
                style={{display:'block', fontSize:12, width:'100%'}}
              />
              <div className="small muted" style={{marginTop:4}}>
                JPG / PNG / PDF · max 10 MB / súbor. Prílohy archivujeme pri žiadosti.
                {files.length > 0 && <> · <b>{files.length} súborov vybratých</b></>}
              </div>
            </div>
          </div>
        )}

        <div className="small muted" style={{background:'var(--blue-50)', padding:'8px 10px', borderRadius:6, lineHeight:1.55}}>
          Pracovných dní: <b style={{color:'var(--ink-900)'}}>{days}</b>
          {rem && <> · Zostatok: <b style={{color: rem.remaining < days ? 'var(--red-500)' : 'var(--ink-900)'}}>{rem.remaining}</b> z {rem.total} {rem.remaining < days && <span style={{color:'var(--red-500)'}}> · prekračujete zostatok</span>}</>}
          <br/>Žiadosť pôjde administrátorovi na schválenie.
        </div>
        {err && <div className="auth-alert" role="alert"><span>{err}</span></div>}
      </form>
    </Modal>
  );
}

function TechnicianServis() {
  const sites = [
    { n:'RD Kučera · Žilina',       kw:9.9,  today:42.3, week:186, month:642, stat:'ok',    last:'pred 2 min' },
    { n:'SolarTech · Madunice',     kw:86,   today:318.5, week:1420, month:5820, stat:'ok',    last:'pred 1 min' },
    { n:'ABW · Bratislava',         kw:800,  today:2840.2, week:14200, month:54100, stat:'warn',  last:'pred 3 min', alert:'Optimizér #24 · nízky výkon' },
    { n:'Penzión Josu · Zuberec',  kw:100,  today:0, week:420, month:2880, stat:'err',  last:'pred 14 min', alert:'Menič 2/2 · chyba ISO F002' },
    { n:'Armovňa Kaplna',           kw:100,  today:385.1, week:1820, month:6640, stat:'ok',    last:'pred 4 min' },
    { n:'Skleníky · Sereď',          kw:250,  today:924.7, week:4120, month:15200, stat:'warn', last:'pred 8 min', alert:'Teplota meniča 68°C' },
  ];
  const statChip = (s) => s==='ok' ? <span className="chip green dot">OK</span> : s==='warn' ? <span className="chip amber dot">Varovanie</span> : <span className="chip red dot">Porucha</span>;
  const urgent = sites.filter(s => s.stat !== 'ok');
  return (
    <AppShell active="ai" crumbs={['ERP','Servis · GoodWe SEMS']}>
      <div className="page-head">
        <div>
          <div className="hstack"><h1 style={{margin:0}}>Technický monitoring</h1><span className="chip green dot">Sync pred 1 min</span></div>
          <p>Napojené na <b>GoodWe SEMS portál zhotoviteľa</b> · 18 inštalácií · 2.4 MW inštalovaný výkon</p>
        </div>
        <div className="page-head-actions">
          <div className="seg">
            <button>Dnes</button>
            <button className="active">Týždeň</button>
            <button>Mesiac</button>
            <button>Vlastný</button>
          </div>
          <button className="btn"><Ico.download/>Report</button>
        </div>
      </div>

      {urgent.length > 0 && (
        <div className="card" style={{borderColor:'var(--red-500)', background:'linear-gradient(0deg, #fff, #fff5f5)', marginBottom:14}}>
          <div style={{padding:'10px 14px', display:'flex', alignItems:'center', gap:10, borderBottom:'1px solid var(--red-100)'}}>
            <div style={{width:32, height:32, borderRadius:8, background:'var(--red-500)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center'}}>
              <Ico.bell/>
            </div>
            <div>
              <b style={{color:'var(--red-500)'}}>Urgentné · {urgent.length} inštalácie vyžadujú pozornosť</b>
              <div className="small muted">Automatické notifikácie odoslané zodpovedným technikom (SMS + e-mail + push).</div>
            </div>
            <button className="btn btn-sm" style={{marginLeft:'auto'}}>Prideliť technika</button>
            <button className="btn btn-sm btn-primary">Otvoriť v SEMS ↗</button>
          </div>
          <div>
            {urgent.map((s,i) => (
              <div key={i} style={{padding:'10px 14px', borderTop: i>0?'1px solid var(--border)':'none', display:'flex', alignItems:'center', gap:10}}>
                <span style={{width:8, height:8, borderRadius:'50%', background: s.stat==='err'?'var(--red-500)':'var(--amber-500)'}}/>
                <b style={{minWidth:200}}>{s.n}</b>
                <span className="small" style={{color:'var(--red-500)', fontWeight:500}}>{s.alert}</span>
                <span className="small muted" style={{marginLeft:'auto'}}>{s.last}</span>
                <button className="btn btn-xs">Detail</button>
                <button className="btn btn-xs btn-amber">Výjazd</button>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="kpi-grid">
        <div className="kpi accent">
          <div className="label">Výroba · týždeň</div>
          <div className="value">22.8 MWh</div>
          <div className="delta up" style={{color:'#7ed9a5'}}><Ico.arrowUp/>+8,2% vs minulý</div>
          <div className="spark"><Sparkline data={[2.1,3.0,2.8,3.4,3.1,3.8,4.6]} color="#f6bf47" w={90} h={32}/></div>
        </div>
        <div className="kpi"><div className="label">Dnes</div><div className="value">4.51 MWh</div><div className="delta up"><Ico.arrowUp/>82% plánu</div></div>
        <div className="kpi"><div className="label">Mesiac</div><div className="value">85.3 MWh</div><div className="delta up"><Ico.arrowUp/>+12%</div></div>
        <div className="kpi"><div className="label">Aktívne poruchy</div><div className="value" style={{color:'var(--red-500)'}}>2</div><div className="delta" style={{color:'var(--red-500)'}}>● urgentné</div></div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:14, marginBottom:14}}>
        <div className="card">
          <div className="card-head"><h3>Výroba · posledných 7 dní (kWh)</h3><span className="muted small">zdroj GoodWe SEMS</span></div>
          <div className="card-body">
            <svg width="100%" height="180" viewBox="0 0 560 180" preserveAspectRatio="none" style={{overflow:'visible'}}>
              {[0,1,2,3].map(i => <line key={i} x1="0" x2="560" y1={30+i*40} y2={30+i*40} stroke="#e2e8f0" strokeDasharray="3 3"/>)}
              {[2100,3000,2800,3400,3100,3800,4510].map((v,i) => {
                const h = (v/4800)*140;
                const x = 24 + i * 76;
                return <g key={i}><rect x={x} y={170-h} width="52" height={h} rx="4" fill="url(#sg)"/></g>;
              })}
              <defs><linearGradient id="sg" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stopColor="#f3a712"/><stop offset="1" stopColor="#c47a00"/></linearGradient></defs>
            </svg>
          </div>
        </div>
        <div className="card">
          <div className="card-head"><h3>Zdravie inštalácií</h3></div>
          <div className="card-body vstack" style={{gap:10}}>
            <div className="hstack"><span style={{width:10,height:10,borderRadius:50,background:'var(--green-500)'}}/><span style={{flex:1}}>V poriadku</span><b>14</b></div>
            <div className="hstack"><span style={{width:10,height:10,borderRadius:50,background:'var(--amber-500)'}}/><span style={{flex:1}}>Varovanie</span><b>2</b></div>
            <div className="hstack"><span style={{width:10,height:10,borderRadius:50,background:'var(--red-500)'}}/><span style={{flex:1}}>Porucha</span><b>2</b></div>
            <div className="divider"/>
            <div className="small muted">Ø dostupnosť: <b style={{color:'var(--ink-900)'}}>98,7 %</b> · PR (Performance Ratio): <b style={{color:'var(--ink-900)'}}>84,2 %</b></div>
          </div>
        </div>
      </div>

      <div className="card" style={{overflow:'hidden'}}>
        <div className="card-head"><h3>Inštalácie (18)</h3>
          <div className="hstack">
            <input className="input" placeholder="Hľadať…" style={{width:200}}/>
            <select className="select"><option>Všetky stavy</option><option>Poruchy</option></select>
          </div>
        </div>
        <table className="tbl">
          <thead><tr><th>Inštalácia</th><th>Výkon</th><th>Dnes (kWh)</th><th>Týždeň</th><th>Mesiac</th><th>Stav</th><th>Poruchy</th><th>Posledná sync</th><th></th></tr></thead>
          <tbody>
            {sites.map((s,i)=>(
              <tr key={i} className={s.stat!=='ok' ? 'sel' : ''} style={s.stat==='err'?{background:'#fff5f5'}:{}}>
                <td><b>{s.n}</b></td>
                <td>{s.kw} kWp</td>
                <td style={{fontWeight:600}}>{s.today.toFixed(1)}</td>
                <td>{s.week.toLocaleString('sk')} kWh</td>
                <td>{s.month.toLocaleString('sk')} kWh</td>
                <td>{statChip(s.stat)}</td>
                <td>{s.alert ? <span className="small" style={{color:'var(--red-500)', fontWeight:500}}>{s.alert}</span> : <span className="small muted">—</span>}</td>
                <td className="small muted">{s.last}</td>
                <td><button className="btn btn-xs">SEMS ↗</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </AppShell>
  );
}

// ───── Responsive helper (mobile preview of dashboard) ─────
function ResponsivePreview() {
  return (
    <div style={{display:'flex', gap:20, alignItems:'flex-start', justifyContent:'center', padding:'20px 0', background:'#f0eee9'}}>
      <div style={{width:390, height:760, borderRadius:26, border:'10px solid #0b1a2e', overflow:'hidden', boxShadow:'0 20px 60px rgba(0,0,0,0.25)', background:'#fff', flexShrink:0}}>
        <div style={{height:28, background:'#0b1a2e', display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 14px', color:'#fff', fontSize:10, fontWeight:600}}>
          <span>9:41</span><span>•••</span>
        </div>
        <div style={{height:'100%', background:'#0e2744', color:'#fff', display:'flex', alignItems:'center', padding:'10px 14px', gap:10, borderBottom:'1px solid rgba(255,255,255,0.1)'}}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="4" x2="20" y1="12" y2="12"/><line x1="4" x2="20" y1="6" y2="6"/><line x1="4" x2="20" y1="18" y2="18"/></svg>
          <Logo size={26}/>
          <div style={{fontSize:13, fontWeight:700}}>D&amp;D ERP</div>
          <span style={{marginLeft:'auto', width:8, height:8, borderRadius:'50%', background:'#f3a712'}}/>
        </div>
        <div style={{padding:14, background:'#f6f8fc', height:'calc(100% - 86px)', overflow:'auto'}}>
          <div style={{fontSize:15, fontWeight:700}}>Dobrý deň, Dávid</div>
          <div style={{fontSize:11, color:'#5b6b82', marginBottom:12}}>Štvrtok 23. apríl</div>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginBottom:10}}>
            <div style={{background:'linear-gradient(135deg, #0e2744, #133258)', color:'#fff', padding:10, borderRadius:8}}>
              <div style={{fontSize:9, color:'#a6c0df'}}>OBRAT 7D</div>
              <div style={{fontSize:16, fontWeight:700}}>87,4k €</div>
              <div style={{fontSize:10, color:'#7ed9a5'}}>↑ +12,4%</div>
            </div>
            <div style={{background:'#fff', padding:10, borderRadius:8, border:'1px solid #e2e8f0'}}>
              <div style={{fontSize:9, color:'#5b6b82'}}>NOVÉ</div>
              <div style={{fontSize:16, fontWeight:700}}>12</div>
              <div style={{fontSize:10, color:'#f3a712'}}>● akcia</div>
            </div>
          </div>
          <div style={{background:'#fff', borderRadius:8, border:'1px solid #e2e8f0', padding:10, marginBottom:10}}>
            <div style={{fontSize:11.5, fontWeight:600, marginBottom:6}}>Posledné objednávky</div>
            {['#DD-2841 · 4 782 €','#DD-2840 · 12 450 €','#DD-2839 · 1 240 €'].map(o => (
              <div key={o} style={{fontSize:11, padding:'5px 0', borderTop:'1px solid #eef2f7', display:'flex', justifyContent:'space-between'}}>
                <span>{o.split(' · ')[0]}</span><b>{o.split(' · ')[1]}</b>
              </div>
            ))}
          </div>
          <div style={{background:'#fff5f5', border:'1px solid #fce1e1', borderRadius:8, padding:10, marginBottom:10}}>
            <div style={{fontSize:11.5, fontWeight:600, color:'#d64545'}}>⚠ 2 inštalácie hlásia poruchu</div>
            <div style={{fontSize:10.5, color:'#5b6b82', marginTop:2}}>Penzión Josu · ABW Bratislava</div>
          </div>
          <button style={{width:'100%', height:38, borderRadius:8, background:'#f3a712', border:'none', fontWeight:600, fontSize:12}}>+ Nová žiadosť o voľno</button>
        </div>
      </div>

      <div style={{width:640, height:760, borderRadius:18, border:'8px solid #0b1a2e', overflow:'hidden', boxShadow:'0 20px 60px rgba(0,0,0,0.25)', flexShrink:0, background:'#f6f8fc'}}>
        <div style={{display:'flex', height:'100%'}}>
          <div style={{width:52, background:'#0e2744', color:'#fff', display:'flex', flexDirection:'column', alignItems:'center', gap:12, padding:'14px 0'}}>
            <Logo size={26}/>
            <div style={{width:30, height:30, borderRadius:6, background:'rgba(255,255,255,0.08)', display:'flex', alignItems:'center', justifyContent:'center'}}><Ico.dashboard/></div>
            <div style={{width:30, height:30, borderRadius:6, display:'flex', alignItems:'center', justifyContent:'center', color:'#b8c9e0'}}><Ico.orders/></div>
            <div style={{width:30, height:30, borderRadius:6, display:'flex', alignItems:'center', justifyContent:'center', color:'#b8c9e0'}}><Ico.products/></div>
            <div style={{width:30, height:30, borderRadius:6, display:'flex', alignItems:'center', justifyContent:'center', color:'#b8c9e0'}}><Ico.ai/></div>
            <div style={{width:30, height:30, borderRadius:6, display:'flex', alignItems:'center', justifyContent:'center', color:'#b8c9e0'}}><Ico.users/></div>
          </div>
          <div style={{flex:1, padding:14, overflow:'auto'}}>
            <div style={{fontSize:15, fontWeight:700}}>Servis · GoodWe SEMS</div>
            <div style={{fontSize:11, color:'#5b6b82', marginBottom:10}}>18 inštalácií · 2.4 MW</div>
            <div style={{background:'#fff5f5', border:'1px solid #fce1e1', borderRadius:8, padding:10, marginBottom:10}}>
              <div style={{fontSize:12, fontWeight:600, color:'#d64545'}}>⚠ 2 urgentné poruchy</div>
              <div style={{fontSize:11, marginTop:4}}>• Penzión Josu · Menič 2/2 chyba ISO F002</div>
              <div style={{fontSize:11}}>• ABW Bratislava · Optimizér #24</div>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:6, marginBottom:10}}>
              {[['Dnes','4.5 MWh'],['Týždeň','22.8'],['Mesiac','85.3']].map(([a,b]) => (
                <div key={a} style={{background:'#fff', border:'1px solid #e2e8f0', borderRadius:6, padding:8}}>
                  <div style={{fontSize:9, color:'#5b6b82', textTransform:'uppercase'}}>{a}</div>
                  <div style={{fontSize:14, fontWeight:700}}>{b}</div>
                </div>
              ))}
            </div>
            <div style={{background:'#fff', borderRadius:8, border:'1px solid #e2e8f0', padding:10}}>
              <div style={{fontSize:12, fontWeight:600, marginBottom:6}}>Inštalácie</div>
              {[['ABW Bratislava','800 kWp','warn'],['SolarTech Madunice','86 kWp','ok'],['Penzión Zuberec','100 kWp','err']].map(([n,p,s],i) => (
                <div key={i} style={{display:'flex', alignItems:'center', gap:6, padding:'6px 0', borderTop: i>0?'1px solid #eef2f7':'none', fontSize:11}}>
                  <span style={{width:6,height:6,borderRadius:'50%', background: s==='ok'?'#2a9d5f':s==='warn'?'#f3a712':'#d64545'}}/>
                  <span style={{flex:1}}>{n}</span>
                  <span style={{color:'#5b6b82'}}>{p}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CalendarLeave, TechnicianServis, ResponsivePreview });
