// Admin nézet — felhasználók, jogosultságok, költségvetés/scope/időzítés szerkesztés

// ─── Edit-mode toggle (közös) ─────────────────────────────────────────────
const EditToggle = ({ on, setOn }) => (
  <button
    className={'btn sm ' + (on ? 'accent' : 'ghost')}
    onClick={() => setOn(!on)}
    style={{ gap: 6 }}
    aria-pressed={on}>
    <Icon name={on ? 'check' : 'edit'} size={13}/>
    {on ? 'Kész' : 'Szerkesztés'}
  </button>
);

// ─── Admin Kezdő — projekt áttekintés ─────────────────────────────────────

const logCost = (l) => l.numWorkers * l.hoursPerWorker * l.hourlyRate + (l.materialCost || 0);

const AdminHome = ({ user, setView }) => {
  const totalBudget = window.totalBudget();
  const totalSpent = window.totalSpent();
  const totalPending = window.totalPending();
  const totalPaid = window.totalPaid();
  const pct = totalBudget ? (totalSpent / totalBudget) * 100 : 0;

  const today = window.TODAY;
  const todayMs = new Date(today).getTime();
  const sevenDaysAgo = todayMs - 7 * 86400000;

  // Fázisok
  const activePhases = window.PHASES.filter(p => {
    const s = new Date(p.start).getTime(), e = new Date(p.end).getTime();
    return s <= todayMs && todayMs <= e;
  });
  const overduePhases = window.PHASES.filter(p => new Date(p.end).getTime() < todayMs)
    .filter(p => {
      const tasks = window.PARENT_TASKS.filter(t => t.phaseId === p.id);
      const total = tasks.reduce((s, t) => s + t.budget, 0);
      const sp = window.phaseSpent(p.id);
      return total > 0 && sp / total < 0.95;
    });

  // Munkanapló
  const pendingLogs = window.WORK_LOGS.filter(l => l.status === 'pending');
  const recentLogs = window.WORK_LOGS.slice()
    .sort((a, b) => b.date.localeCompare(a.date))
    .slice(0, 5);
  const activeContractors = new Set(
    window.WORK_LOGS.filter(l => new Date(l.date).getTime() >= sevenDaysAgo).map(l => l.contractorId)
  );

  // Kifizetésre vár (jóváhagyott − kifizetett)
  const totalDebt = window.getContractors().reduce((s, c) => s + Math.max(0, window.contractorBalance(c.id)), 0);

  return (
    <div className="main fade-in">
      <div>
        <div className="eyebrow">Projekt · {user.name}</div>
        <h2 style={{ marginTop: 4 }}>H1 · áttekintés</h2>
      </div>

      {/* Költségvetés szalag */}
      <div className="card" style={{ padding: 16, background: 'var(--ink)', color: 'var(--bg)', border: 'none' }}>
        <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.6)' }}>Teljes költségvetés</div>
        <div className="num" style={{ fontSize: 32, fontWeight: 600, marginTop: 4, letterSpacing: '-0.02em' }}>
          {window.formatHufShort(totalBudget)} Ft
        </div>
        <div style={{ height: 8, background: 'rgba(255,255,255,0.1)', borderRadius: 999, marginTop: 12, overflow: 'hidden' }}>
          <div style={{ width: pct + '%', height: '100%', background: 'var(--accent)' }}/>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginTop: 14, fontSize: 11 }}>
          <div>
            <div style={{ opacity: 0.6 }}>Elköltve</div>
            <div className="num" style={{ fontSize: 14, fontWeight: 600 }}>{window.formatHufShort(totalSpent)}</div>
          </div>
          <div>
            <div style={{ opacity: 0.6 }}>Várakozik</div>
            <div className="num" style={{ fontSize: 14, fontWeight: 600 }}>{window.formatHufShort(totalPending)}</div>
          </div>
          <div>
            <div style={{ opacity: 0.6 }}>Kifizetve</div>
            <div className="num" style={{ fontSize: 14, fontWeight: 600 }}>{window.formatHufShort(totalPaid)}</div>
          </div>
        </div>
      </div>

      {/* KPI sor */}
      <div className="desk-grid-3" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
        <DashStat label="Jóváhagyásra vár" value={pendingLogs.length} sub={window.formatHufShort(totalPending) + ' Ft'} accent="warn"/>
        <DashStat label="Kifizetésre vár" value={window.formatHufShort(totalDebt)} sub="Ft · vállalkozóknak" accent="ink"/>
        <DashStat label="Aktív vállalkozó" value={activeContractors.size} sub="elmúlt 7 nap"/>
      </div>

      {/* Aktív fázisok */}
      <div className="stack-2">
        <div className="row between">
          <div className="eyebrow">Aktív fázisok · {activePhases.length}</div>
          <button className="bare" onClick={() => setView('timeline')} style={{ fontSize: 11, color: 'var(--ink-3)' }}>Ütemterv →</button>
        </div>
        {activePhases.length === 0 && <div className="muted" style={{ fontSize: 12 }}>Jelenleg nincs futó fázis.</div>}
        {activePhases.map(p => {
          const tasks = window.PARENT_TASKS.filter(t => t.phaseId === p.id);
          const total = tasks.reduce((s, t) => s + t.budget, 0);
          const sp = window.phaseSpent(p.id);
          const sMs = new Date(p.start).getTime(), eMs = new Date(p.end).getTime();
          const elapsed = ((todayMs - sMs) / (eMs - sMs)) * 100;
          return (
            <div key={p.id} className="card" style={{ padding: 12 }}>
              <div className="row" style={{ gap: 10, alignItems: 'center' }}>
                <span style={{ width: 4, height: 30, background: p.color, borderRadius: 2 }}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="row between">
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{p.code}</span>
                      <span style={{ fontWeight: 500, marginLeft: 8, fontSize: 14 }}>{p.name}</span>
                    </div>
                    <span className="num muted" style={{ fontSize: 11, marginLeft: 8 }}>{Math.max(0, Math.round((eMs - todayMs) / 86400000))} nap</span>
                  </div>
                  <BudgetBar spent={sp} budget={total} height={4}/>
                  <div className="row between" style={{ marginTop: 4 }}>
                    <span className="muted" style={{ fontSize: 10 }}>idő · {Math.round(elapsed)}%</span>
                    <span className="num muted" style={{ fontSize: 10 }}>költés · {total ? Math.round((sp/total)*100) : 0}%</span>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Lemaradt fázisok */}
      {overduePhases.length > 0 && (
        <div className="card" style={{ padding: 12, background: 'var(--bad-l)', borderColor: 'rgba(220,38,38,0.2)' }}>
          <div className="row" style={{ gap: 8, alignItems: 'center' }}>
            <Icon name="warn" size={16} stroke={2.2}/>
            <div style={{ fontWeight: 600, fontSize: 13, color: 'var(--bad)' }}>{overduePhases.length} fázis lemaradásban</div>
          </div>
          <div style={{ marginTop: 8, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {overduePhases.map(p => (
              <button key={p.id} className="pill" onClick={() => setView('timing')}
                style={{ background: 'var(--bg)', border: '1px solid rgba(220,38,38,0.25)', color: 'var(--bad)', fontSize: 11, fontWeight: 500 }}>
                {p.code} {p.name}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Legutóbbi aktivitás */}
      <div className="stack-2">
        <div className="eyebrow">Legutóbbi aktivitás</div>
        <div className="card" style={{ padding: 0 }}>
          {recentLogs.map((l, i) => {
            const c = window.getUser(l.contractorId);
            const ph = window.getPhase(l.phaseId);
            const cost = logCost(l);
            const statusColor = l.status === 'paid' ? 'var(--ok)' : l.status === 'approved' ? 'var(--accent)' : l.status === 'pending' ? 'var(--warn)' : 'var(--ink-3)';
            const statusLabel = l.status === 'paid' ? 'kifizetve' : l.status === 'approved' ? 'jóváhagyva' : l.status === 'pending' ? 'várakozik' : l.status;
            return (
              <div key={l.id} style={{ padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10, borderTop: i === 0 ? 'none' : '1px solid var(--line-2)' }}>
                {c && <Avatar user={c} size={28}/>}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c ? c.name : '—'}</div>
                  <div className="muted" style={{ fontSize: 11, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {ph && <span className="mono" style={{ marginRight: 6 }}>{ph.code}</span>}
                    {l.description}
                  </div>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <div className="num" style={{ fontSize: 12, fontWeight: 500 }}>{window.formatHufShort(cost)}</div>
                  <div style={{ fontSize: 10, color: statusColor, fontWeight: 600 }}>{statusLabel}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Beállítások szekció — kompakt linkek a 4 admin részhez */}
      <div className="stack-2">
        <div className="eyebrow">Beállítások</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <SettingsLink icon="users" label="Felhasználók" sub={window.USERS.length + ' fő'} onClick={() => setView('users')}/>
          <SettingsLink icon="forint" label="Költségvetés és scope" sub={window.PHASES.length + ' fázis · ' + window.PARENT_TASKS.length + ' tétel'} onClick={() => setView('budget')}/>
          <SettingsLink icon="cal" label="Időzítés" sub="fázis dátumok" onClick={() => setView('timing')}/>
          <SettingsLink icon="shield" label="Jogosultságok" sub="szerep szerint" onClick={() => setView('permissions')}/>
        </div>
      </div>
    </div>
  );
};

const DashStat = ({ label, value, sub, accent = 'ink' }) => {
  const colors = { ink: 'var(--ink)', warn: '#8A6200', ok: 'var(--ok)' };
  return (
    <div className="card" style={{ padding: 10 }}>
      <div className="muted" style={{ fontSize: 10, fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
      <div className="num" style={{ fontSize: 18, fontWeight: 600, marginTop: 2, color: colors[accent] || colors.ink }}>{value}</div>
      {sub && <div className="muted" style={{ fontSize: 10, marginTop: 1 }}>{sub}</div>}
    </div>
  );
};

const SettingsLink = ({ icon, label, sub, onClick }) => (
  <button className="card tap" onClick={onClick}
    style={{ padding: 12, textAlign: 'left', display: 'flex', alignItems: 'center', gap: 10, background: 'var(--surface)' }}>
    <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--surface-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
      <Icon name={icon} size={16}/>
    </div>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontWeight: 500, fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</div>
      <div className="muted" style={{ fontSize: 10, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sub}</div>
    </div>
    <Icon name="chevron-r" size={14}/>
  </button>
);

// (legacy ActionTile — már nem használjuk a kezdőn, de export miatt itt marad)
const ActionTile = ({ icon, label, sub, onClick }) => (
  <button className="card tap" onClick={onClick} style={{ padding: 14, textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 8, background: 'var(--surface)' }}>
    <Icon name={icon} size={22}/>
    <div>
      <div style={{ fontWeight: 600, fontSize: 14 }}>{label}</div>
      <div className="muted" style={{ fontSize: 11 }}>{sub}</div>
    </div>
  </button>
);

// ─── Felhasználók ─────────────────────────────────────────────────────────

const AdminUsers = () => {
  const [, force] = React.useReducer(x => x + 1, 0);
  const [edit, setEdit] = React.useState(false);
  const [showNew, setShowNew] = React.useState(false);
  const [editUser, setEditUser] = React.useState(null);
  const [confirmDel, setConfirmDel] = React.useState(null);
  return (
    <div className="main fade-in">
      <div className="row between">
        <h2>Felhasználók</h2>
        <div className="row" style={{ gap: 8 }}>
          {edit && <button className="btn accent sm" onClick={() => setShowNew(true)}><Icon name="plus" size={14}/> Új</button>}
          <EditToggle on={edit} setOn={setEdit}/>
        </div>
      </div>

      {['admin', 'approver', 'contractor'].map(role => {
        const roleUsers = window.USERS.filter(u => u.role === role);
        const labels = { admin: 'Adminok', approver: 'Jóváhagyók', contractor: 'Vállalkozók' };
        return (
          <div key={role} className="stack-2">
            <div className="eyebrow">{labels[role]} · {roleUsers.length}</div>
            {roleUsers.map(u => (
              <div key={u.id} className="card" style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 12 }}>
                <Avatar user={u}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 500, fontSize: 14 }}>{u.name}</div>
                  <div className="muted mono" style={{ fontSize: 11 }}>{u.email}</div>
                  {u.skill && <div className="muted" style={{ fontSize: 11 }}>{u.skill} · {window.formatHufShort(u.hourlyRate)} Ft/óra</div>}
                </div>
                {edit && <button className="btn ghost sm" onClick={() => setEditUser(u)} aria-label="Szerkesztés"><Icon name="edit" size={14}/></button>}
              </div>
            ))}
          </div>
        );
      })}

      {showNew && (
        <UserSheet onClose={() => setShowNew(false)} onSave={async (data) => {
          try {
            await window.api.users.save(data);
            await window.refreshData();
          } catch (err) { alert(window.apiErrorMessage(err)); }
          setShowNew(false); force();
        }}/>
      )}

      {editUser && (
        <UserSheet user={editUser} onClose={() => setEditUser(null)}
          onDelete={() => { setConfirmDel(editUser); setEditUser(null); }}
          onSave={async (data) => {
            try {
              await window.api.users.save({ id: editUser.id, ...data });
              await window.refreshData();
            } catch (err) { alert(window.apiErrorMessage(err)); }
            // Optimistic local update so the sheet closes responsively even
            // if the server is slow.
            Object.assign(editUser, data);
            setEditUser(null); force();
          }}/>
      )}

      {confirmDel && (
        <Sheet open onClose={() => setConfirmDel(null)} title="Felhasználó törlése">
          <div style={{ fontSize: 14 }}>
            Biztosan törölni szeretnéd: <b>{confirmDel.name}</b>?
          </div>
          <div className="row" style={{ gap: 8, marginTop: 16 }}>
            <button className="btn full" onClick={() => setConfirmDel(null)}>Mégse</button>
            <button className="btn full" style={{ background: 'var(--bad)', color: '#fff' }} onClick={async () => {
              try {
                await window.api.users.del(confirmDel.id);
                await window.refreshData();
              } catch (err) { alert(window.apiErrorMessage(err)); }
              const i = window.USERS.findIndex(x => x.id === confirmDel.id);
              if (i >= 0) window.USERS.splice(i, 1);
              setConfirmDel(null); force();
            }}>Törlés</button>
          </div>
        </Sheet>
      )}
    </div>
  );
};

// ─── Költségvetés és scope szerkesztő ─────────────────────────────────────

const AdminBudget = () => {
  const [, force] = React.useReducer(x => x + 1, 0);
  const [edit, setEdit] = React.useState(false);
  const [openPhase, setOpenPhase] = React.useState(null);
  const [editTask, setEditTask] = React.useState(null);
  const [newTaskFor, setNewTaskFor] = React.useState(null);
  const [editPhase, setEditPhase] = React.useState(null);
  const [newPhase, setNewPhase] = React.useState(false);
  const [confirmDel, setConfirmDel] = React.useState(null);

  return (
    <div className="main fade-in">
      <div className="row between">
        <h2>Költségvetés és scope</h2>
        <div className="row" style={{ gap: 8 }}>
          {edit && <button className="btn accent sm" onClick={() => setNewPhase(true)}><Icon name="plus" size={14}/> Új fázis</button>}
          <EditToggle on={edit} setOn={setEdit}/>
        </div>
      </div>
      <div className="muted" style={{ fontSize: 13 }}>
        {edit
          ? 'Fázisok és tételek hozzáadása, szerkesztése, törlése. A változások azonnal megjelennek a vállalkozói és jóváhagyói nézetekben.'
          : 'Fázisok és tételek áttekintése. Szerkesztéshez kapcsold be a Szerkesztés módot.'}
      </div>

      <div className="stack-2">
        {window.PHASES.map(p => {
          const tasks = window.PARENT_TASKS.filter(t => t.phaseId === p.id);
          const total = tasks.reduce((s, t) => s + t.budget, 0);
          const spent = window.phaseSpent(p.id);
          const pct = total > 0 ? (spent / total) * 100 : 0;
          const isOpen = openPhase === p.id;
          return (
            <div key={p.id} className="card" style={{ padding: 0 }}>
              <div style={{ padding: 12, display: 'flex', alignItems: 'center', gap: 10 }}>
                <span className="phase-stripe" style={{ background: p.color, width: 4, height: 36, borderRadius: 2 }}/>
                <button className="bare tap" onClick={() => setOpenPhase(isOpen ? null : p.id)}
                  style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
                  <div className="row between">
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{p.code}</span>
                      <span style={{ fontWeight: 500, marginLeft: 8 }}>{p.name}</span>
                    </div>
                    <span className="num" style={{ fontWeight: 600, fontSize: 13, marginLeft: 8 }}>{window.formatHufShort(total)} Ft</span>
                  </div>
                  <div className="row" style={{ marginTop: 6, gap: 10 }}>
                    <BudgetBar spent={spent} budget={total} height={4}/>
                    <span className="num muted" style={{ fontSize: 10, minWidth: 30, textAlign: 'right' }}>{Math.round(pct)}%</span>
                  </div>
                </button>
                <button className="btn ghost sm" title="Fázis szerkesztése" onClick={() => setEditPhase(p)} style={{ padding: 6, display: edit ? '' : 'none' }}><Icon name="edit" size={14}/></button>
                <button className="btn ghost sm" title="Fázis törlése" onClick={() => setConfirmDel({ kind: 'phase', target: p })} style={{ padding: 6, display: edit ? '' : 'none' }}><Icon name="trash" size={14}/></button>
                <button className="bare" onClick={() => setOpenPhase(isOpen ? null : p.id)} style={{ padding: 4 }}>
                  <Icon name={isOpen ? 'chevron-d' : 'chevron-r'} size={16}/>
                </button>
              </div>
              {isOpen && (
                <div style={{ borderTop: '1px solid var(--line-2)' }}>
                  {tasks.length === 0 && (
                    <div className="muted" style={{ padding: 14, fontSize: 12, textAlign: 'center' }}>Még nincs tétel ebben a fázisban.</div>
                  )}
                  {tasks.map(t => {
                    const sp = window.parentTaskSpent(t.id);
                    return (
                      <div key={t.id} style={{ padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10, borderTop: '1px solid var(--line-2)' }}>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 500 }}>{t.name}</div>
                          <BudgetBar spent={sp} budget={t.budget} height={3}/>
                        </div>
                        <div className="num" style={{ fontSize: 12, fontWeight: 500, minWidth: 84, textAlign: 'right' }}>{window.formatHufShort(t.budget)} Ft</div>
                        <button className="btn ghost sm" onClick={() => setEditTask({ task: t, phase: p })} style={{ padding: 6, display: edit ? '' : 'none' }}><Icon name="edit" size={14}/></button>
                        <button className="btn ghost sm" onClick={() => setConfirmDel({ kind: 'task', target: t })} style={{ padding: 6, display: edit ? '' : 'none' }}><Icon name="trash" size={14}/></button>
                      </div>
                    );
                  })}
                  {edit && (
                    <div style={{ padding: 10, textAlign: 'center', borderTop: '1px solid var(--line-2)' }}>
                      <button className="btn sm" onClick={() => setNewTaskFor(p)}><Icon name="plus" size={14}/> Új tétel</button>
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Új tétel sheet */}
      {newTaskFor && (
        <TaskSheet phase={newTaskFor} onClose={() => setNewTaskFor(null)} onSave={async (data) => {
          try {
            await window.api.parentTasks.save({ phase_id: newTaskFor.id, name: data.name, budget: data.budget });
            await window.refreshData();
          } catch (err) { alert(window.apiErrorMessage(err)); }
          setNewTaskFor(null); force();
        }}/>
      )}

      {/* Tétel szerkesztés */}
      {editTask && (
        <TaskSheet task={editTask.task} phase={editTask.phase} onClose={() => setEditTask(null)} onSave={async (data) => {
          try {
            await window.api.parentTasks.save({ id: editTask.task.id, phase_id: editTask.phase.id, name: data.name, budget: data.budget });
            await window.refreshData();
          } catch (err) { alert(window.apiErrorMessage(err)); }
          editTask.task.name = data.name;
          editTask.task.budget = data.budget;
          setEditTask(null); force();
        }}/>
      )}

      {/* Új fázis */}
      {newPhase && (
        <PhaseSheet onClose={() => setNewPhase(false)} onSave={async (data) => {
          try {
            await window.api.phases.save(data);
            await window.refreshData();
          } catch (err) { alert(window.apiErrorMessage(err)); }
          setNewPhase(false); force();
        }}/>
      )}

      {/* Fázis szerkesztés */}
      {editPhase && (
        <PhaseSheet phase={editPhase} onClose={() => setEditPhase(null)} onSave={async (data) => {
          try {
            await window.api.phases.save({ id: editPhase.id, ...data });
            await window.refreshData();
          } catch (err) { alert(window.apiErrorMessage(err)); }
          Object.assign(editPhase, data);
          setEditPhase(null); force();
        }}/>
      )}

      {/* Törlés megerősítés */}
      {confirmDel && (
        <Sheet open onClose={() => setConfirmDel(null)} title="Törlés">
          <div style={{ fontSize: 14 }}>
            Biztosan törölni szeretnéd: <b>{confirmDel.target.name}</b>?
            {confirmDel.kind === 'phase' && (
              <div className="muted" style={{ fontSize: 12, marginTop: 6 }}>
                A fázishoz tartozó {window.PARENT_TASKS.filter(t => t.phaseId === confirmDel.target.id).length} tétel is törlődik.
              </div>
            )}
          </div>
          <div className="row" style={{ gap: 8, marginTop: 16 }}>
            <button className="btn full" onClick={() => setConfirmDel(null)}>Mégse</button>
            <button className="btn full" style={{ background: 'var(--bad)', color: '#fff' }} onClick={async () => {
              try {
                if (confirmDel.kind === 'task') {
                  await window.api.parentTasks.del(confirmDel.target.id);
                } else {
                  await window.api.phases.del(confirmDel.target.id);
                }
                await window.refreshData();
              } catch (err) { alert(window.apiErrorMessage(err)); }
              if (confirmDel.kind === 'task') {
                const i = window.PARENT_TASKS.findIndex(x => x.id === confirmDel.target.id);
                if (i >= 0) window.PARENT_TASKS.splice(i, 1);
              } else {
                const phaseId = confirmDel.target.id;
                window.PARENT_TASKS = window.PARENT_TASKS.filter(t => t.phaseId !== phaseId);
                const i = window.PHASES.findIndex(x => x.id === phaseId);
                if (i >= 0) window.PHASES.splice(i, 1);
              }
              setConfirmDel(null); force();
            }}>Törlés</button>
          </div>
        </Sheet>
      )}
    </div>
  );
};

const TaskSheet = ({ task, phase, onClose, onSave }) => {
  const [name, setName] = React.useState(task ? task.name : '');
  const [budget, setBudget] = React.useState(task ? task.budget : 0);
  const valid = name.trim().length > 0 && budget >= 0;
  return (
    <Sheet open onClose={onClose} title={task ? 'Tétel szerkesztése' : 'Új tétel'}>
      <div className="stack-2">
        <div className="muted" style={{ fontSize: 12 }}>
          <span className="mono">{phase.code}</span> · {phase.name}
        </div>
        <div className="field">
          <label className="label">Tétel neve</label>
          <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Pl. Falazás új falak"/>
        </div>
        <div className="field">
          <label className="label">Költségvetés (Ft)</label>
          <input className="input num" type="number" value={budget} onChange={e => setBudget(+e.target.value || 0)}/>
          <div className="muted mono" style={{ fontSize: 11, marginTop: 4 }}>{window.formatHuf(budget)} Ft</div>
        </div>
        <div className="row" style={{ gap: 8, marginTop: 8 }}>
          <button className="btn full" onClick={onClose}>Mégse</button>
          <button className="btn accent full" disabled={!valid} onClick={() => onSave({ name: name.trim(), budget })}>Mentés</button>
        </div>
      </div>
    </Sheet>
  );
};

const PALETTE = ['#6805E1', '#1482FA', '#1AAA9B', '#B2DE78', '#FFBD3B', '#F15922', '#F68069', '#9D4DFF', '#3DC1B5', '#4DA6FF', '#C8E89A', '#FFD370', '#FF8551', '#7DA8FF', '#030630'];

const PhaseSheet = ({ phase, onClose, onSave }) => {
  const [name, setName] = React.useState(phase ? phase.name : '');
  const [color, setColor] = React.useState(phase ? phase.color : PALETTE[0]);
  const [start, setStart] = React.useState(phase ? phase.start : '2026-01-01');
  const [end, setEnd] = React.useState(phase ? phase.end : '2026-12-31');
  const valid = name.trim().length > 0 && start && end && start <= end;
  return (
    <Sheet open onClose={onClose} title={phase ? 'Fázis szerkesztése' : 'Új fázis'}>
      <div className="stack-2">
        <div className="field">
          <label className="label">Fázis neve</label>
          <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Pl. Tetőszerkezet"/>
        </div>
        <div className="row" style={{ gap: 10 }}>
          <div className="field" style={{ flex: 1 }}>
            <label className="label">Kezdés</label>
            <input className="input" type="date" value={start} onChange={e => setStart(e.target.value)}/>
          </div>
          <div className="field" style={{ flex: 1 }}>
            <label className="label">Vége</label>
            <input className="input" type="date" value={end} onChange={e => setEnd(e.target.value)}/>
          </div>
        </div>
        <div className="field">
          <label className="label">Szín</label>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {PALETTE.map(c => (
              <button key={c} className="bare tap" onClick={() => setColor(c)} style={{
                width: 28, height: 28, borderRadius: 8, background: c,
                border: color === c ? '2px solid var(--ink)' : '2px solid transparent',
                boxShadow: color === c ? '0 0 0 2px var(--bg) inset' : 'none'
              }}/>
            ))}
          </div>
        </div>
        <div className="row" style={{ gap: 8, marginTop: 8 }}>
          <button className="btn full" onClick={onClose}>Mégse</button>
          <button className="btn accent full" disabled={!valid} onClick={() => onSave({ name: name.trim(), color, start, end })}>Mentés</button>
        </div>
      </div>
    </Sheet>
  );
};

// ─── Időzítés (timeline szerkesztő) ───────────────────────────────────────

const AdminTiming = () => {
  const [, force] = React.useReducer(x => x + 1, 0);
  const [edit, setEdit] = React.useState(false);
  const [editPhase, setEditPhase] = React.useState(null);
  const [newPhase, setNewPhase] = React.useState(false);

  // mini-Gantt domain
  const allDates = window.PHASES.flatMap(p => [p.start, p.end]).filter(Boolean).sort();
  const min = allDates[0] || '2026-01-01';
  const max = allDates[allDates.length - 1] || '2026-12-31';
  const minMs = new Date(min).getTime();
  const maxMs = new Date(max).getTime();
  const span = Math.max(1, maxMs - minMs);
  const todayMs = Date.now();
  const todayPct = ((todayMs - minMs) / span) * 100;

  const monthMarks = [];
  {
    const d = new Date(minMs);
    d.setDate(1);
    while (d.getTime() <= maxMs) {
      const pct = ((d.getTime() - minMs) / span) * 100;
      monthMarks.push({ pct, label: d.toLocaleDateString('hu-HU', { month: 'short' }) });
      d.setMonth(d.getMonth() + 1);
    }
  }

  return (
    <div className="main fade-in">
      <div className="row between">
        <h2>Időzítés</h2>
        <div className="row" style={{ gap: 8 }}>
          {edit && <button className="btn accent sm" onClick={() => setNewPhase(true)}><Icon name="plus" size={14}/> Új fázis</button>}
          <EditToggle on={edit} setOn={setEdit}/>
        </div>
      </div>
      <div className="muted" style={{ fontSize: 13 }}>
        {edit
          ? 'Módosítsd a kezdő és záró dátumokat. A piros szín jelzi a lemaradt szakaszokat.'
          : 'Fázisok időzítése és lemaradások. Szerkesztéshez kapcsold be a Szerkesztés módot.'}
      </div>

      {/* Mini-Gantt */}
      <div className="card" style={{ padding: 12, overflowX: 'auto' }}>
        <div style={{ minWidth: 520, position: 'relative' }}>
          {/* hónap vonalak */}
          <div style={{ position: 'relative', height: 18, marginBottom: 6 }}>
            {monthMarks.map((m, i) => (
              <div key={i} style={{ position: 'absolute', left: m.pct + '%', transform: 'translateX(-50%)', fontSize: 9, color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{m.label}</div>
            ))}
          </div>
          {/* sávok */}
          <div style={{ position: 'relative' }}>
            {/* ma vonal */}
            {todayPct >= 0 && todayPct <= 100 && (
              <div style={{ position: 'absolute', left: todayPct + '%', top: 0, bottom: 0, width: 2, background: 'var(--accent)', zIndex: 2 }}>
                <div style={{ position: 'absolute', top: -14, left: -10, fontSize: 9, color: 'var(--accent)', fontWeight: 700 }}>MA</div>
              </div>
            )}
            {window.PHASES.map(p => {
              const sMs = new Date(p.start).getTime();
              const eMs = new Date(p.end).getTime();
              const left = ((sMs - minMs) / span) * 100;
              const width = Math.max(1, ((eMs - sMs) / span) * 100);
              const overdue = eMs < todayMs;
              return (
                <button key={p.id} className="bare tap" onClick={() => setEditPhase(p)}
                  style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '6px 0', textAlign: 'left' }}>
                  <div style={{ width: 110, fontSize: 11, color: 'var(--ink-2)', flexShrink: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    <span className="mono" style={{ color: 'var(--ink-3)' }}>{p.code}</span> {p.name}
                  </div>
                  <div style={{ flex: 1, position: 'relative', height: 18, background: 'var(--surface-2)', borderRadius: 4 }}>
                    <div style={{
                      position: 'absolute', left: left + '%', width: width + '%', top: 0, bottom: 0,
                      background: overdue ? 'var(--bad)' : p.color, borderRadius: 4,
                      opacity: overdue ? 0.9 : 1
                    }}/>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      </div>

      {/* Lista — közvetlen dátum szerkesztés */}
      <div className="stack-2">
        <div className="eyebrow">Fázisok időzítése</div>
        {window.PHASES.map(p => {
          const sMs = new Date(p.start).getTime();
          const eMs = new Date(p.end).getTime();
          const days = Math.round((eMs - sMs) / 86400000) + 1;
          const overdue = eMs < todayMs;
          return (
            <div key={p.id} className="card" style={{ padding: 12 }}>
              <div className="row" style={{ gap: 10, alignItems: 'center' }}>
                <span style={{ width: 4, height: 30, background: p.color, borderRadius: 2 }}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="row between">
                    <div>
                      <span className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{p.code}</span>
                      <span style={{ fontWeight: 500, marginLeft: 8, fontSize: 14 }}>{p.name}</span>
                    </div>
                    {overdue && <span className="pill" style={{ background: 'var(--bad-l)', color: 'var(--bad)', fontSize: 10, fontWeight: 600 }}>LEMARADT</span>}
                  </div>
                  <div className="muted" style={{ fontSize: 11, marginTop: 2 }}>{days} nap</div>
                </div>
              </div>
              <div className="row" style={{ gap: 8, marginTop: 10 }}>
                <div style={{ flex: 1 }}>
                  <label className="label" style={{ fontSize: 10 }}>Kezdés</label>
                  {edit
                    ? <input className="input" type="date" value={p.start} onChange={e => { p.start = e.target.value; force(); }}
                        onBlur={async (e) => {
                          try { await window.api.phases.save({ id: p.id, name: p.name, color: p.color, start: e.target.value, end: p.end }); await window.refreshData(); }
                          catch (err) { alert(window.apiErrorMessage(err)); }
                        }}/>
                    : <div className="num" style={{ fontSize: 13, padding: '8px 0' }}>{p.start}</div>}
                </div>
                <div style={{ flex: 1 }}>
                  <label className="label" style={{ fontSize: 10 }}>Vége</label>
                  {edit
                    ? <input className="input" type="date" value={p.end} onChange={e => { p.end = e.target.value; force(); }}
                        onBlur={async (e) => {
                          try { await window.api.phases.save({ id: p.id, name: p.name, color: p.color, start: p.start, end: e.target.value }); await window.refreshData(); }
                          catch (err) { alert(window.apiErrorMessage(err)); }
                        }}/>
                    : <div className="num" style={{ fontSize: 13, padding: '8px 0' }}>{p.end}</div>}
                </div>
                {edit && <button className="btn ghost sm" onClick={() => setEditPhase(p)} style={{ padding: 6, alignSelf: 'flex-end' }} title="Részletek"><Icon name="edit" size={14}/></button>}
              </div>
            </div>
          );
        })}
      </div>

      {editPhase && (
        <PhaseSheet phase={editPhase} onClose={() => setEditPhase(null)} onSave={async (data) => {
          try {
            await window.api.phases.save({ id: editPhase.id, ...data });
            await window.refreshData();
          } catch (err) { alert(window.apiErrorMessage(err)); }
          Object.assign(editPhase, data);
          setEditPhase(null); force();
        }}/>
      )}

      {newPhase && (
        <PhaseSheet onClose={() => setNewPhase(false)} onSave={async (data) => {
          try {
            await window.api.phases.save(data);
            await window.refreshData();
          } catch (err) { alert(window.apiErrorMessage(err)); }
          setNewPhase(false); force();
        }}/>
      )}
    </div>
  );
};

// ─── Jogosultságok ────────────────────────────────────────────────────────

const AdminPermissions = () => {
  const [, force] = React.useReducer(x => x + 1, 0);
  const [edit, setEdit] = React.useState(false);
  const matrix = [
    { name: 'Saját teljesítések rögzítése',          c: true,  ap: true,  ad: true },
    { name: 'Mások teljesítéseinek megtekintése',     c: false, ap: true,  ad: true },
    { name: 'Teljesítések jóváhagyása',               c: false, ap: true,  ad: true },
    { name: 'Kifizetés rögzítése',                    c: false, ap: true,  ad: true },
    { name: 'Számla beolvasás (OCR)',                 c: false, ap: true,  ad: true },
    { name: 'Költségvetés megtekintése',              c: 'p',   ap: true,  ad: true },
    { name: 'Költségvetés szerkesztése',              c: false, ap: false, ad: true },
    { name: 'Dashboard megtekintése',                 c: 'p',   ap: true,  ad: true },
    { name: 'Ütemterv megtekintése',                  c: true,  ap: true,  ad: true },
    { name: 'Ütemterv szerkesztése',                  c: false, ap: false, ad: true },
    { name: 'Dokumentum feltöltés',                   c: true,  ap: true,  ad: true },
    { name: 'Felhasználók kezelése',                  c: false, ap: false, ad: true },
    { name: 'Jogosultságok beállítása',               c: false, ap: false, ad: true },
  ];

  return (
    <div className="main fade-in">
      <div className="row between">
        <h2>Jogosultságok</h2>
        <EditToggle on={edit} setOn={setEdit}/>
      </div>
      <div className="muted" style={{ fontSize: 13 }}>
        {edit
          ? 'Kattints egy cellára a jogosultság váltásához (✓ → részleges → —).'
          : 'Szerep szerinti alapértékek. Finomhangoláshoz kapcsold be a Szerkesztés módot, vagy a Felhasználók nézetben állítsd egyénenként.'}
      </div>

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', background: 'var(--surface-2)', padding: '10px 12px', fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
          <div>Funkció</div>
          <div style={{ textAlign: 'center' }}>Vállalkozó</div>
          <div style={{ textAlign: 'center' }}>Jóváhagyó</div>
          <div style={{ textAlign: 'center' }}>Admin</div>
        </div>
        {matrix.map((m, i) => {
          const cycle = (key) => {
            const v = m[key];
            m[key] = v === true ? 'p' : v === 'p' ? false : true;
            force();
          };
          return (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', padding: '11px 12px', fontSize: 13, borderTop: '1px solid var(--line-2)', alignItems: 'center' }}>
              <div>{m.name}</div>
              <PermCell v={m.c}  edit={edit} onClick={() => cycle('c')}/>
              <PermCell v={m.ap} edit={edit} onClick={() => cycle('ap')}/>
              <PermCell v={m.ad} edit={edit} onClick={() => cycle('ad')}/>
            </div>
          );
        })}
      </div>

      <Hint>
        A 'p' = részleges (pl. csak saját adatok láthatók). Az adminisztrátor finomhangolhatja egyénileg, hogy egy-egy vállalkozó láthassa-e a Dashboardot.
      </Hint>
    </div>
  );
};

const PermCell = ({ v, edit, onClick }) => {
  const inner = v === true
    ? <Icon name="check" size={16} stroke={2.4}/>
    : v === 'p'
      ? <span style={{ color: 'var(--warn)', fontSize: 11, fontWeight: 600 }}>részleges</span>
      : <span style={{ color: 'var(--ink-4)' }}>—</span>;
  if (edit) {
    return (
      <button className="bare tap" onClick={onClick}
        style={{ textAlign: 'center', padding: 6, borderRadius: 6, background: 'var(--surface-2)' }}>
        {inner}
      </button>
    );
  }
  return <div style={{ textAlign: 'center' }}>{inner}</div>;
};

const ROLE_OPTIONS = [
  { v: 'contractor', l: 'Vállalkozó' },
  { v: 'approver',   l: 'Jóváhagyó' },
  { v: 'admin',      l: 'Admin' },
];

const UserSheet = ({ user, onClose, onSave, onDelete }) => {
  const [name, setName] = React.useState(user ? user.name : '');
  const [email, setEmail] = React.useState(user ? user.email : '');
  const [phone, setPhone] = React.useState(user ? user.phone || '' : '');
  const [role, setRole] = React.useState(user ? user.role : 'contractor');
  const [skill, setSkill] = React.useState(user ? user.skill || '' : '');
  const [hourlyRate, setHourlyRate] = React.useState(user ? user.hourlyRate || 0 : 5000);
  const [password, setPassword] = React.useState('');
  const [showPwd, setShowPwd] = React.useState(false);
  const valid = name.trim().length > 0 && email.trim().length > 0 && (!password || password.length >= 6);
  return (
    <Sheet open onClose={onClose} title={user ? 'Felhasználó szerkesztése' : 'Új felhasználó'}>
      <div className="stack-2">
        <div className="field"><label className="label">Név</label><input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Pl. Kovács Anna"/></div>
        <div className="field"><label className="label">Email</label><input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="email@példa.hu"/></div>
        <div className="field"><label className="label">Szerep</label>
          <select className="select" value={role} onChange={e => setRole(e.target.value)}>
            {ROLE_OPTIONS.map(o => <option key={o.v} value={o.v}>{o.l}</option>)}
          </select>
        </div>
        <div className="field"><label className="label">Telefon</label><input className="input" value={phone} onChange={e => setPhone(e.target.value)}/></div>
        {role === 'contractor' && (
          <>
            <div className="field"><label className="label">Szakág</label><input className="input" value={skill} onChange={e => setSkill(e.target.value)} placeholder="Pl. Kőműves"/></div>
            <div className="field"><label className="label">Óradíj (Ft)</label><input className="input num" type="number" value={hourlyRate} onChange={e => setHourlyRate(+e.target.value || 0)}/></div>
          </>
        )}
        <div className="field">
          <label className="label">Jelszó {user && <span className="muted" style={{ fontWeight: 400 }}>(üresen hagyva nem változik)</span>}</label>
          <div className="row" style={{ gap: 6 }}>
            <input className="input" type={showPwd ? 'text' : 'password'} value={password} onChange={e => setPassword(e.target.value)}
              placeholder={user ? '••••••••' : 'Új jelszó (min. 6 karakter)'}
              autoComplete="new-password" style={{ flex: 1 }}/>
            <button className="btn ghost sm" onClick={() => setShowPwd(!showPwd)} title={showPwd ? 'Elrejt' : 'Megjelenít'} style={{ padding: 8 }}>
              <Icon name="eye" size={16}/>
            </button>
          </div>
          {!user && !password && (
            <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>Üresen hagyva alapértelmezett jelszó: <span className="mono">h1demo</span></div>
          )}
          {password && password.length > 0 && password.length < 6 && (
            <div style={{ color: 'var(--danger)', fontSize: 11, marginTop: 4 }}>Min. 6 karakter</div>
          )}
        </div>
        <div className="row" style={{ gap: 8, marginTop: 8 }}>
          <button className="btn full" onClick={onClose}>Mégse</button>
          <button className="btn accent full" disabled={!valid} onClick={() => onSave({
            name: name.trim(), email: email.trim(), phone, role,
            ...(role === 'contractor' ? { skill, hourlyRate } : {}),
            ...(password ? { password } : {}),
          })}>Mentés</button>
        </div>
        {user && onDelete && (
          <button className="btn ghost sm" onClick={onDelete} style={{ marginTop: 8, color: 'var(--bad)' }}><Icon name="trash" size={14}/> Felhasználó törlése</button>
        )}
      </div>
    </Sheet>
  );
};

Object.assign(window, { AdminHome, AdminUsers, AdminBudget, AdminTiming, AdminPermissions, ActionTile, PermCell, TaskSheet, PhaseSheet, UserSheet });
