// Megosztott nézetek: Dashboard, Ütemterv (Gantt), Dokumentumok

const Dashboard = ({ user }) => {
  const [, force] = React.useReducer(x => x + 1, 0);
  const [edit, setEdit] = React.useState(false);
  const [openPhaseId, 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);

  const totalBudget = window.totalBudget();
  const totalSpent  = window.totalSpent();
  const totalPending= window.totalPending();
  const totalPaid   = window.totalPaid();

  const isAdmin = user?.role === 'admin';

  return (
    <div className="main fade-in">
      <div className="row between" style={{ alignItems: 'flex-start', gap: 12 }}>
        <div>
          <div className="eyebrow">Projekt</div>
          <h2 style={{ marginTop: 4 }}>Hogy állunk</h2>
        </div>
        {isAdmin && (
          <button className={'btn sm ' + (edit ? 'accent' : '')} onClick={() => setEdit(!edit)}>
            <Icon name={edit ? 'check' : 'edit'} size={14}/> {edit ? 'Kész' : 'Szerkesztés'}
          </button>
        )}
      </div>

      {/* Pénzügyi áttekintés */}
      <div className="card" style={{ padding: 16 }}>
        <div className="row between">
          <div>
            <div className="eyebrow">Összköltségvetés</div>
            <div className="num" style={{ fontSize: 28, fontWeight: 600, marginTop: 2 }}>{window.formatHufShort(totalBudget)} Ft</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="eyebrow">Elköltve</div>
            <div className="num" style={{ fontSize: 18, fontWeight: 600, marginTop: 2 }}>{Math.round(totalSpent / totalBudget * 100)}%</div>
          </div>
        </div>
        <BudgetBar spent={totalSpent} pending={totalPending} budget={totalBudget} height={12}/>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 8, marginTop: 14, fontSize: 11 }}>
          <Mini label="Jóváhagyott"  value={totalSpent}/>
          <Mini label="Várakozik"    value={totalPending} color="var(--warn)"/>
          <Mini label="Kifizetve"    value={totalPaid}    color="var(--info)"/>
          <Mini label="Maradék"      value={totalBudget - totalSpent - totalPending} color="var(--ok)"/>
        </div>
      </div>

      {/* Fázisok bontva */}
      <div className="stack-2">
        <div className="row between">
          <h3>Fázisonként</h3>
          {edit && (
            <button className="btn accent sm" onClick={() => setNewPhase(true)}>
              <Icon name="plus" size={14}/> Új fázis
            </button>
          )}
        </div>
        {window.PHASES.map(p => {
          const total = window.phaseBudget(p.id);
          const spent = window.phaseSpent(p.id);
          if (total === 0 && !edit) return null;
          const tasks = window.PARENT_TASKS.filter(t => t.phaseId === p.id);
          const isOpen = edit && openPhaseId === p.id;
          return (
            <div key={p.id} className="card" style={{ padding: 0 }}>
              <div style={{ padding: 12, display: 'flex', gap: 12, alignItems: 'center' }}>
                <span className="phase-stripe" style={{ background: p.color, height: 32, width: 4 }}/>
                <button className="bare tap" onClick={() => edit && setOpenPhase(isOpen ? null : p.id)}
                  style={{ flex: 1, minWidth: 0, textAlign: 'left', cursor: edit ? 'pointer' : 'default' }}>
                  <div className="row between">
                    <div style={{ fontSize: 13, fontWeight: 500, minWidth: 0 }}>
                      <span className="mono muted">{p.code}</span> {p.name}
                    </div>
                  </div>
                  <BudgetBar spent={spent} budget={total} height={4}/>
                </button>
                <div style={{ textAlign: 'right', minWidth: 70 }}>
                  <div className="num" style={{ fontSize: 12, fontWeight: 600 }}>{window.formatHufShort(spent)}</div>
                  <div className="num muted" style={{ fontSize: 10 }}>/ {window.formatHufShort(total)}</div>
                </div>
                {edit && (
                  <div className="row" style={{ gap: 2 }}>
                    <button className="btn ghost sm" title="Fázis szerkesztése" onClick={() => setEditPhase(p)} style={{ padding: 6 }}><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 }}><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>
                )}
              </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', whiteSpace: 'nowrap' }}>{window.formatHufShort(t.budget)} Ft</div>
                        <button className="btn ghost sm" onClick={() => setEditTask({ task: t, phase: p })} style={{ padding: 6 }}><Icon name="edit" size={14}/></button>
                        <button className="btn ghost sm" onClick={() => setConfirmDel({ kind: 'task', target: t })} style={{ padding: 6 }}><Icon name="trash" size={14}/></button>
                      </div>
                    );
                  })}
                  <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>

      {/* Edit sheets — admin */}
      {newTaskFor && (
        <window.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();
        }}/>
      )}
      {editTask && (
        <window.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();
        }}/>
      )}
      {newPhase && (
        <window.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();
        }}/>
      )}
      {editPhase && (
        <window.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();
        }}/>
      )}
      {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 Mini = ({ label, value, color = 'var(--ink)' }) => (
  <div>
    <div style={{ color: 'var(--ink-3)' }}>{label}</div>
    <div className="num" style={{ fontWeight: 600, color, fontSize: 13 }}>{window.formatHufShort(value)}</div>
  </div>
);

// === Ütemterv (Gantt mobil-barát) ===
const Timeline = ({ user }) => {
  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);
  const isAdmin = user?.role === 'admin';
  const today = new Date(window.TODAY);
  const phases = edit ? window.PHASES : window.PHASES.filter(p => window.phaseBudget(p.id) > 0);
  if (phases.length === 0) {
    return (
      <div className="main fade-in">
        <h2>Ütemterv</h2>
        <div className="muted">Még nincs fázis.</div>
      </div>
    );
  }

  // Időablak: legkorábbi start → legkésőbbi end
  const dates = phases.flatMap(p => [new Date(p.start), new Date(p.end)]);
  const minD = new Date(Math.min(...dates));
  const maxD = new Date(Math.max(...dates));
  const totalDays = (maxD - minD) / 86400000;

  // Hónap-fejléc
  const months = [];
  let cur = new Date(minD.getFullYear(), minD.getMonth(), 1);
  while (cur <= maxD) {
    months.push(new Date(cur));
    cur = new Date(cur.getFullYear(), cur.getMonth() + 1, 1);
  }
  const monthLabels = ['jan', 'feb', 'már', 'ápr', 'máj', 'jún', 'júl', 'aug', 'szept', 'okt', 'nov', 'dec'];

  const todayPct = ((today - minD) / 86400000) / totalDays * 100;

  return (
    <div className="main fade-in">
      <div className="row between" style={{ alignItems: 'flex-start', gap: 12 }}>
        <h2>Ütemterv</h2>
        {isAdmin && (
          <button className={'btn sm ' + (edit ? 'accent' : '')} onClick={() => setEdit(!edit)}>
            <Icon name={edit ? 'check' : 'edit'} size={14}/> {edit ? 'Kész' : 'Szerkesztés'}
          </button>
        )}
      </div>
      <div className="muted" style={{ fontSize: 13 }}>
        {edit
          ? 'Kattints egy fázisra a kezdő/záró dátum vagy név módosításához.'
          : 'Tervezett ütemezés. A piros sávok lemaradásban vannak a mai naphoz képest.'}
      </div>

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        {/* Hónap fejléc */}
        <div style={{ overflowX: 'auto', padding: 12, borderBottom: '1px solid var(--line)' }}>
          <div style={{ minWidth: 800, position: 'relative', height: 22 }}>
            {months.map((m, i) => {
              const pct = ((m - minD) / 86400000) / totalDays * 100;
              return (
                <div key={i} style={{ position: 'absolute', left: pct + '%', fontSize: 10, color: 'var(--ink-3)', fontFamily: 'Inter', fontWeight: 500, borderLeft: '1px solid var(--line)', paddingLeft: 4, height: 22 }}>
                  {monthLabels[m.getMonth()]} <span style={{ opacity: 0.6 }}>{String(m.getFullYear()).slice(2)}</span>
                </div>
              );
            })}
            {/* Today marker */}
            <div style={{ position: 'absolute', left: todayPct + '%', top: 0, width: 1, height: 22, background: 'var(--accent)' }}/>
          </div>
        </div>

        {/* Sávok */}
        <div style={{ overflowX: 'auto', padding: '4px 0' }}>
          <div style={{ minWidth: 800, position: 'relative' }}>
            {phases.map((p, i) => {
              const start = new Date(p.start);
              const end   = new Date(p.end);
              const startPct = ((start - minD) / 86400000) / totalDays * 100;
              const widthPct = ((end - start) / 86400000) / totalDays * 100;
              const overdue = today > end && window.phaseSpent(p.id) < window.phaseBudget(p.id) * 0.95;
              const inProgress = today >= start && today <= end;
              const done = window.phaseSpent(p.id) >= window.phaseBudget(p.id) * 0.95;
              const progressPct = window.phaseBudget(p.id) > 0
                ? Math.min(100, (window.phaseSpent(p.id) / window.phaseBudget(p.id)) * 100) : 0;

              return (
                <div key={p.id} className={edit ? 'tap' : ''} onClick={edit ? () => setEditPhase(p) : undefined}
                  style={{ display: 'flex', alignItems: 'center', padding: '6px 12px', gap: 10, borderBottom: i < phases.length - 1 ? '1px solid var(--line-2)' : 'none', cursor: edit ? 'pointer' : 'default' }}>
                  <div style={{ width: 140, flexShrink: 0, fontSize: 12, fontWeight: 500, lineHeight: 1.2, display: 'flex', alignItems: 'center', gap: 4 }}>
                    <span className="mono muted" style={{ fontSize: 10, marginRight: 6 }}>{p.code}</span>
                    <span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</span>
                    {edit && <Icon name="edit" size={12} stroke={2}/>}
                  </div>
                  <div style={{ flex: 1, position: 'relative', height: 24 }}>
                    {/* Today line */}
                    <div style={{ position: 'absolute', left: todayPct + '%', top: -4, bottom: -4, width: 1, background: 'var(--accent)', opacity: 0.5, zIndex: 2 }}/>
                    {/* Bar */}
                    <div style={{
                      position: 'absolute', left: startPct + '%', width: widthPct + '%', top: 4, height: 16,
                      background: overdue ? 'var(--danger-l)' : 'var(--line-2)',
                      borderRadius: 4, overflow: 'hidden', border: overdue ? '1px solid var(--danger)' : '1px solid var(--line)'
                    }}>
                      <div style={{
                        width: progressPct + '%', height: '100%',
                        background: overdue ? 'var(--danger)' : (done ? 'var(--ok)' : (inProgress ? p.color : 'var(--ink-4)')),
                        opacity: inProgress ? 1 : 0.8,
                      }}/>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Legenda */}
      <div className="row" style={{ gap: 14, fontSize: 11, flexWrap: 'wrap' }}>
        <span className="row" style={{ gap: 6 }}><span style={{ width: 10, height: 10, background: 'var(--ok)', borderRadius: 2 }}/>kész</span>
        <span className="row" style={{ gap: 6 }}><span style={{ width: 10, height: 10, background: 'var(--accent)', borderRadius: 2 }}/>folyamatban</span>
        <span className="row" style={{ gap: 6 }}><span style={{ width: 10, height: 10, background: 'var(--danger)', borderRadius: 2 }}/>lemaradásban</span>
        <span className="row" style={{ gap: 6 }}><span style={{ width: 1, height: 12, background: 'var(--accent)' }}/>ma ({window.formatDate(window.TODAY)})</span>
      </div>

      {edit && (
        <button className="btn accent" onClick={() => setNewPhase(true)} style={{ alignSelf: 'flex-start' }}>
          <Icon name="plus" size={14}/> Új fázis
        </button>
      )}

      {editPhase && (
        <window.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 && (
        <window.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>
  );
};

// === Dokumentumok ===
const Documents = ({ user }) => {
  const [filter, setFilter] = React.useState('all');
  const [showUpload, setShowUpload] = React.useState(false);

  const tags = ['all', ...Object.keys(window.TAG_COLORS)];
  const docs = filter === 'all' ? window.DOCUMENTS : window.DOCUMENTS.filter(d => d.tag === filter);

  return (
    <div className="main fade-in">
      <div className="row between">
        <h2>Dokumentumok</h2>
        <button className="btn accent sm" onClick={() => setShowUpload(true)}><Icon name="upload" size={14}/> Feltölt</button>
      </div>

      {/* Tag szűrő */}
      <div className="chip-row">
        {tags.map(t => {
          const color = window.TAG_COLORS[t];
          const active = filter === t;
          return (
            <button key={t} className={'chip ' + (active ? 'active' : '')} onClick={() => setFilter(t)}
              style={{ flexShrink: 0, ...(active && color ? { background: color, borderColor: color } : {}) }}>
              {color && <span className="dot" style={{ background: active ? 'white' : color }}/>}
              {t === 'all' ? 'Mind' : t}
            </button>
          );
        })}
      </div>

      <div className="stack-2">
        {docs.map(d => {
          const u = window.getUser(d.uploadedBy);
          const tagColor = window.TAG_COLORS[d.tag];
          return (
            <a key={d.id} className="card tap" href={d.url || d.downloadUrl || '#'} target="_blank" rel="noreferrer"
               style={{ padding: 12, display: 'flex', gap: 12, alignItems: 'center', textDecoration: 'none', color: 'inherit' }}>
              <div style={{ width: 40, height: 48, background: 'var(--surface-2)', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Inter', fontSize: 9, fontWeight: 700, color: 'var(--ink-3)', flexShrink: 0, border: '1px solid var(--line)' }}>
                {(d.type || '').toUpperCase()}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.3 }}>{d.name}</div>
                <div className="row" style={{ gap: 6, marginTop: 6, fontSize: 11 }}>
                  <span className="chip" style={{ background: tagColor + '22', color: tagColor, border: 'none', padding: '3px 8px' }}>{d.tag}</span>
                  <span className="muted">{u?.name?.split(' ')[0]} · {window.relativeDay(d.uploadedAt)} · {d.size}</span>
                </div>
              </div>
              <span className="btn ghost sm"><Icon name="download" size={16}/></span>
            </a>
          );
        })}
      </div>

      {showUpload && <DocumentUploadSheet onClose={() => setShowUpload(false)}/>}
    </div>
  );
};

const DocumentUploadSheet = ({ onClose }) => {
  const [file, setFile] = React.useState(null);
  const [name, setName] = React.useState('');
  const [tag, setTag] = React.useState(Object.keys(window.TAG_COLORS)[0] || '');
  const [busy, setBusy] = React.useState(false);
  const fileRef = React.useRef(null);

  const onPick = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    setFile(f);
    if (!name) setName(f.name.replace(/\.[^.]+$/, ''));
  };

  const submit = async () => {
    if (!file || !name.trim() || !tag) return;
    setBusy(true);
    try {
      const fd = new FormData();
      fd.append('file', file);
      fd.append('name', name.trim());
      fd.append('tag', tag);
      await window.api.documents.upload(fd);
      await window.refreshData();
      onClose();
    } catch (err) {
      alert(window.apiErrorMessage(err));
    } finally {
      setBusy(false);
    }
  };

  return (
    <Sheet open onClose={onClose} title="Új dokumentum">
      <div className="stack-2">
        <input ref={fileRef} type="file" accept=".pdf,.jpg,.jpeg,.png,image/*" style={{ display: 'none' }} onChange={onPick}/>
        <button className="card tap" onClick={() => fileRef.current?.click()}
          style={{ padding: 30, textAlign: 'center', borderStyle: 'dashed', borderColor: 'var(--accent)', display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'center', color: 'var(--accent-d)' }}>
          <Icon name="upload" size={28}/>
          <div style={{ fontWeight: 500 }}>{file ? file.name : 'Fájl választása'}</div>
          <div className="muted" style={{ fontSize: 11 }}>PDF, JPG, PNG, max 100 MB</div>
        </button>
        <div className="field">
          <label className="label">Név</label>
          <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Pl. Belsőépítészeti koncepció v4"/>
        </div>
        <div className="field">
          <label className="label">Címke</label>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {Object.keys(window.TAG_COLORS).map(t => {
              const c = window.TAG_COLORS[t];
              const active = tag === t;
              return (
                <button key={t} className="chip" onClick={() => setTag(t)}
                  style={{ background: active ? c : c + '22', color: active ? '#fff' : c, border: active ? '1px solid ' + c : 'none' }}>
                  {t}
                </button>
              );
            })}
          </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={busy || !file || !name.trim() || !tag} onClick={submit}>
            {busy ? 'Feltöltés…' : 'Feltöltés'}
          </button>
        </div>
      </div>
    </Sheet>
  );
};

Object.assign(window, { Dashboard, Timeline, Documents, DocumentUploadSheet, Mini });
