// --- Agenda / Eventi schedulati — versione Libro ------------------------
const EVENT_TYPES = [
  { id: 'reminder',  label: 'Promemoria', icon: 'bell' },
  { id: 'deadline',  label: 'Scadenza',   icon: 'alert-triangle' },
  { id: 'recurring', label: 'Ricorrente', icon: 'repeat' },
];

function AgendaScreen() {
  const [events, setEvents] = useState([]);
  const [tasks, setTasks] = useState([]);
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState(null);

  const load = () => {
    setLoading(true);
    Promise.all([
      apiT('/api/events').catch(() => []),
      apiT('/api/tasks').catch(() => []),
      apiT('/api/projects').catch(() => []),
    ]).then(([ev, ts, ps]) => { setEvents(ev); setTasks(ts); setProjects(ps); setLoading(false); });
  };
  useEffect(load, []);

  const destroy = async (id) => {
    if (!confirm('Eliminare evento?')) return;
    try { await apiT('/api/events/' + id, { method: 'DELETE' }); load(); }
    catch (e) { alert(e.message); }
  };
  const toggleActive = async (ev) => {
    try { await apiT('/api/events/' + ev.id, { method: 'PATCH', body: { active: ev.active ? 0 : 1 } }); load(); }
    catch (e) { alert(e.message); }
  };

  const active = events.filter((e) => e.active);
  const byType = {
    reminder: active.filter((e) => e.event_type === 'reminder'),
    deadline: active.filter((e) => e.event_type === 'deadline'),
    recurring: active.filter((e) => e.event_type === 'recurring'),
  };

  return (
    <>
      <Topbar crumbs={['Gestionale', 'Produttività', 'Agenda']} />
      <div className="content">
        <div className="page-head">
          <div>
            <h1 className="page-title">Agenda <em>{active.length}</em></h1>
            <div className="page-sub">Promemoria · Scadenze · Eventi ricorrenti</div>
          </div>
          <button className="btn btn-accent btn-lg" onClick={() => { setEditing(null); setShowForm(true); }}>
            <Icon name="plus" size={15} /> Nuovo evento
          </button>
        </div>

        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-3)' }}>Caricamento…</div>
        ) : active.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-3)' }}>
            <Icon name="calendar-days" size={24} style={{ margin: '0 auto 10px' }} />
            <div>Nessun evento programmato</div>
            <div style={{ marginTop: 10 }}><button className="btn btn-accent" onClick={() => { setEditing(null); setShowForm(true); }}><Icon name="plus" size={13} /> Crea il primo</button></div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {EVENT_TYPES.map((t) => byType[t.id].length > 0 && (
              <div key={t.id}>
                <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 6 }}>
                  <Icon name={t.icon} size={12} /> {t.label} <span style={{ color: 'var(--ink-2)' }}>({byType[t.id].length})</span>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {byType[t.id].map((ev) => {
                    const task = ev.task_id ? tasks.find((x) => x.id === ev.task_id) : null;
                    const proj = ev.project_id ? projects.find((x) => x.id === ev.project_id) : null;
                    return (
                      <div key={ev.id}
                        className="card" style={{ background: '#fff', border: '1px solid var(--rule)', borderRadius: 10, padding: '12px 14px', display: 'grid', gridTemplateColumns: '1fr auto', gap: 10, alignItems: 'center', cursor: 'pointer' }}
                        onClick={() => { setEditing(ev); setShowForm(true); }}>
                        <div>
                          <div style={{ fontSize: 14, fontWeight: 500 }}>{ev.title}</div>
                          {ev.description && <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{ev.description}</div>}
                          <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
                            {ev.scheduled_time && <span>⏰ {ev.scheduled_time.includes('T') ? fmtDate(ev.scheduled_time.slice(0,10)) + ' ' + ev.scheduled_time.slice(11,16) : ev.scheduled_time.slice(0,5)}</span>}
                            {ev.recurrence && <span>🔁 {({ daily: 'Giornaliero', weekdays: 'Lun-Ven', custom: ev.recurrence_days || 'Custom' })[ev.recurrence] || ev.recurrence}</span>}
                            {task && <span style={{ color: 'var(--accent)' }}>📋 {task.title}</span>}
                            {proj && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: proj.color }} />{proj.name}</span>}
                          </div>
                        </div>
                        <div style={{ display: 'flex', gap: 4 }} onClick={(e) => e.stopPropagation()}>
                          <button className="ia" onClick={() => toggleActive(ev)} title={ev.active ? 'Disattiva' : 'Attiva'}>
                            <Icon name={ev.active ? 'bell' : 'bell-off'} size={13} />
                          </button>
                          <button className="ia" onClick={() => destroy(ev.id)} title="Elimina"><Icon name="trash-2" size={13} /></button>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
      {showForm && <EventForm initial={editing} tasks={tasks} projects={projects} onClose={() => setShowForm(false)} onSaved={() => { setShowForm(false); load(); }} />}
    </>
  );
}

function EventForm({ initial, tasks, projects, onClose, onSaved }) {
  const [f, setF] = useState({
    title: '', description: '', event_type: 'reminder',
    scheduled_time: '', recurrence: '', recurrence_days: '',
    task_id: '', project_id: '', active: 1,
    ...(initial || {}),
  });
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState('');
  const set = (k) => (e) => {
    let v = e.target.type === 'checkbox' ? (e.target.checked ? 1 : 0) : e.target.value;
    setF({ ...f, [k]: v });
  };
  const submit = async (e) => {
    e.preventDefault();
    setSaving(true); setErr('');
    try {
      const payload = {
        title: f.title, description: f.description || null,
        event_type: f.event_type,
        scheduled_time: f.scheduled_time || null,
        recurrence: f.event_type === 'recurring' ? f.recurrence : null,
        recurrence_days: f.event_type === 'recurring' && f.recurrence === 'custom' ? f.recurrence_days : null,
        task_id: f.task_id || null, project_id: f.project_id || null,
        active: f.active ? 1 : 0,
      };
      if (initial?.id) await apiT('/api/events/' + initial.id, { method: 'PATCH', body: payload });
      else await apiT('/api/events', { method: 'POST', body: payload });
      onSaved();
    } catch (e) { setErr(e.message); }
    finally { setSaving(false); }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <form className="modal" onClick={(e) => e.stopPropagation()} onSubmit={submit} style={{ width: 540 }}>
        <div className="modal-head">
          <div>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{initial?.id ? 'Modifica' : 'Nuovo'} evento</div>
            <h2 style={{ fontFamily: 'Fraunces', fontSize: 20, fontWeight: 500, margin: '4px 0 0' }}>{f.title || 'Evento'}</h2>
          </div>
          <button type="button" className="btn btn-ic btn-ghost" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>
        <div className="modal-body" style={{ maxHeight: '70vh', overflowY: 'auto' }}>
          {err && <div className="err" style={{ marginBottom: 12 }}><Icon name="alert-circle" size={14} /> {err}</div>}
          <div className="field"><label className="label">Titolo *</label>
            <input className="input" required autoFocus value={f.title} onChange={set('title')} />
          </div>
          <div className="field"><label className="label">Descrizione</label>
            <textarea className="textarea" rows={2} value={f.description || ''} onChange={set('description')} />
          </div>
          <div className="field"><label className="label">Tipo</label>
            <select className="input" value={f.event_type} onChange={set('event_type')}>
              {EVENT_TYPES.map((t) => <option key={t.id} value={t.id}>{t.label}</option>)}
            </select>
          </div>
          <div className="field"><label className="label">{f.event_type === 'recurring' ? 'Orario (HH:MM)' : 'Data + orario'}</label>
            <input className="input mono" type={f.event_type === 'recurring' ? 'time' : 'datetime-local'} value={f.scheduled_time || ''} onChange={set('scheduled_time')} />
          </div>
          {f.event_type === 'recurring' && (
            <>
              <div className="field"><label className="label">Ricorrenza</label>
                <select className="input" value={f.recurrence || ''} onChange={set('recurrence')}>
                  <option value="">— seleziona —</option>
                  <option value="daily">Ogni giorno</option>
                  <option value="weekdays">Lun-Ven</option>
                  <option value="custom">Giorni specifici</option>
                </select>
              </div>
              {f.recurrence === 'custom' && (
                <div className="field"><label className="label">Giorni (0=dom, 1=lun, …, 6=sab, separa con virgola)</label>
                  <input className="input mono" value={f.recurrence_days || ''} onChange={set('recurrence_days')} placeholder="1,3,5" />
                </div>
              )}
            </>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <div className="field"><label className="label">Task collegata</label>
              <select className="input" value={f.task_id || ''} onChange={set('task_id')}>
                <option value="">— nessuna —</option>
                {tasks.filter((t) => t.status !== 'completata').map((t) => <option key={t.id} value={t.id}>{t.title}</option>)}
              </select>
            </div>
            <div className="field"><label className="label">Progetto</label>
              <select className="input" value={f.project_id || ''} onChange={set('project_id')}>
                <option value="">— nessuno —</option>
                {projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
            </div>
          </div>
          <label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, cursor: 'pointer', marginTop: 10 }}>
            <input type="checkbox" checked={!!f.active} onChange={set('active')} /> Attivo
          </label>
        </div>
        <div className="modal-foot">
          <button type="button" className="btn btn-ghost" onClick={onClose}>Annulla</button>
          <div style={{ flex: 1 }} />
          <button className="btn btn-accent" type="submit" disabled={saving}>{saving ? 'Salvo…' : (initial?.id ? 'Salva' : 'Crea evento')}</button>
        </div>
      </form>
    </div>
  );
}

window.AgendaScreen = AgendaScreen;
