/* news.jsx — agenda manuale di eventi/catalizzatori datati.
   Eventi inseriti a mano (lanci, prodotti, IPO...) raggruppati per giorno.
   Niente LLM: è la TUA agenda. CRUD via /api/news-events. */

(function () {
  const { useState, useEffect } = React;

  const _CAT_EMOJI = {
    lancio: "🚀", prodotto: "📱", ipo: "🆕", macro: "🏛️",
    earnings: "📊", regolatorio: "⚖️", roadmap: "🗺️", evento: "📅", altro: "•",
  };

  const _MESI = ["gen", "feb", "mar", "apr", "mag", "giu", "lug", "ago", "set", "ott", "nov", "dic"];
  const _GIORNI = ["dom", "lun", "mar", "mer", "gio", "ven", "sab"];

  function _fmtDay(iso) {
    const d = new Date(iso + "T12:00:00");
    return `${_GIORNI[d.getDay()]} ${d.getDate()} ${_MESI[d.getMonth()]}`;
  }
  function _daysAway(iso) {
    const today = new Date(); today.setHours(0, 0, 0, 0);
    const d = new Date(iso + "T00:00:00");
    return Math.round((d - today) / 86400000);
  }
  function _fmtArtDate(iso) {
    if (!iso) return "";
    const d = new Date(iso + "T12:00:00");
    if (isNaN(d)) return "";
    return `${d.getDate()} ${_MESI[d.getMonth()]}`;
  }

  // Lista IPO/Spin-off (spostata da Top Picks) — con data articolo + publisher
  function DiscoveryList({ events }) {
    if (events === null) return <div className="card muted">Caricamento notizie…</div>;
    const ipo     = events.filter(e => e.type === "ipo");
    const spinoff = events.filter(e => e.type === "spinoff");

    const Group = ({ label, color, list }) => list.length === 0 ? null : (
      <div className="card" style={{ marginBottom: 12 }}>
        <div style={{ fontWeight: 700, fontSize: 13, color, marginBottom: 10,
                      display: "flex", alignItems: "center", gap: 7 }}>
          <span style={{ width: 9, height: 9, borderRadius: "50%", background: color }} />
          {label} <span className="muted" style={{ fontWeight: 500 }}>({list.length})</span>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          {list.map((e, i) => (
            <a key={i} href={e.url || undefined} target="_blank" rel="noopener noreferrer"
               style={{ display: "block", textDecoration: "none", color: "inherit",
                        background: "var(--surface)", borderRadius: 8,
                        padding: "9px 12px", borderLeft: `2px solid ${color}` }}>
              <div style={{ fontWeight: 600, fontSize: 13, lineHeight: 1.35 }}>{e.title}</div>
              <div style={{ display: "flex", gap: 8, alignItems: "center", marginTop: 4 }}>
                {e.published && <span className="badge" style={{ fontSize: 11 }}>🗓 {_fmtArtDate(e.published)}</span>}
                {e.publisher && <span className="muted" style={{ fontSize: 11.5 }}>{e.publisher}</span>}
                {e.url && <span style={{ color: "var(--accent)", fontSize: 11.5, marginLeft: "auto" }}>apri ↗</span>}
              </div>
            </a>
          ))}
        </div>
      </div>
    );

    return (
      <div>
        {events.length === 0 && <div className="card muted">Nessuna notizia IPO/Spin-off al momento.</div>}
        <Group label="IPO imminenti" color="var(--red, #ef4444)" list={ipo} />
        <Group label="Spin-off annunciati" color="#f97316" list={spinoff} />
        <div className="muted" style={{ fontSize: 11.5, marginTop: 4 }}>
          Notizie raccolte da Tool5 (ricerca news, senza ticker). La data è quella dell'articolo;
          le voci si rinnovano ogni giorno. Per eventi tuoi con data certa usa l'Agenda.
        </div>
      </div>
    );
  }

  const _EMPTY_FORM = { event_date: "", event_end_date: "", title: "", symbol: "", category: "lancio", note: "" };

  window.NewsView = function NewsView() {
    const [events, setEvents] = useState([]);
    const [cats, setCats] = useState([]);
    const [showPast, setShowPast] = useState(false);
    const [showForm, setShowForm] = useState(false);
    const [editId, setEditId] = useState(null);          // id evento in modifica | null
    const [confirmDel, setConfirmDel] = useState(null);  // evento da eliminare | null
    const [mode, setMode] = useState("agenda"); // "agenda" | "discovery"
    const [discovery, setDiscovery] = useState(null); // IPO/Spin-off da Tool5
    const [err, setErr] = useState(null);
    const [form, setForm] = useState(_EMPTY_FORM);
    const [saving, setSaving] = useState(false);

    const load = () => {
      fetch("/api/news-events").then(r => r.json()).then(d => {
        if (d.error) setErr(d.error);
        else { setEvents(d.events || []); setCats(d.categories || []); setErr(null); }
      }).catch(e => setErr(String(e)));
    };
    useEffect(load, []);
    useEffect(() => {
      if (mode === "discovery" && discovery === null) {
        fetch("/api/picks/discovery").then(r => r.json())
          .then(d => setDiscovery(d.events || [])).catch(() => setDiscovery([]));
      }
    }, [mode]);

    const closeForm = () => { setShowForm(false); setEditId(null); setForm(_EMPTY_FORM); };

    const save = () => {
      if (!form.event_date || !form.title.trim()) return;
      setSaving(true);
      const isEdit = editId != null;
      fetch(isEdit ? "/api/news-events/update" : "/api/news-events", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify(isEdit ? { id: editId, ...form } : form),
      }).then(r => r.json()).then(() => {
        setSaving(false); closeForm(); load();
      }).catch(() => setSaving(false));
    };

    const startEdit = (ev) => {
      setForm({ event_date: ev.event_date || "", event_end_date: ev.event_end_date || "",
                title: ev.title || "",
                symbol: ev.symbol || "", category: ev.category || "lancio",
                note: ev.note || "" });
      setEditId(ev.id);
      setShowForm(true);
      window.scrollTo?.(0, 0);
    };

    const doDelete = () => {
      const id = confirmDel?.id;
      setConfirmDel(null);
      if (id == null) return;
      setEvents(prev => prev.filter(e => e.id !== id));   // ottimistico
      fetch("/api/news-events/delete", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id }),
      }).then(() => load()).catch(() => load());
    };

    // raggruppa per giorno (di INIZIO), futuri prima; un evento multi-giorno
    // resta visibile finché la sua data di FINE non è passata
    const visible = events.filter(e => showPast || _daysAway(e.event_end_date || e.event_date) >= 0);
    const byDay = {};
    visible.forEach(e => { (byDay[e.event_date] = byDay[e.event_date] || []).push(e); });
    const days = Object.keys(byDay).sort();

    const canSave = form.event_date && form.title.trim() && !saving;

    if (mode === "discovery") {
      return (
        <div className="view-scroll">
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
            <span style={{ fontWeight: 600, fontSize: 16 }}>📰 IPO & Spin-off in arrivo</span>
            <button className="btn btn-sm btn-ghost" onClick={() => setMode("agenda")}>← Agenda</button>
          </div>
          <DiscoveryList events={discovery} />
        </div>
      );
    }

    return (
      <div className="view-scroll">
        {/* barra azioni: l'agenda ha la precedenza, il form è a scomparsa */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12, gap: 8, flexWrap: "wrap" }}>
          <span style={{ fontWeight: 600, fontSize: 16 }}>Agenda eventi</span>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn btn-sm btn-ghost" onClick={() => setMode("discovery")}
                    title="Notizie IPO e Spin-off in arrivo (Tool5)">📰 IPO / Spin-off</button>
            <button className={"btn btn-sm " + (showForm ? "btn-ghost" : "btn-primary")}
                    onClick={() => showForm ? closeForm() : setShowForm(true)}>
              {showForm ? "✕ Chiudi" : "＋ Aggiungi"}
            </button>
          </div>
        </div>

        {/* form aggiunta/modifica (collassabile) */}
        {showForm && (
        <div className="card">
          {editId != null && (
            <div style={{ fontWeight: 700, fontSize: 13, marginBottom: 10, color: "var(--accent)" }}>
              ✎ Modifica evento
            </div>
          )}
          <div className="news-form-grid">
            <div className="field" style={{ maxWidth: 180 }}>
              <label>Data</label>
              <input className="input" type="date" value={form.event_date}
                     onChange={e => setForm({ ...form, event_date: e.target.value })} />
            </div>
            <div className="field" style={{ maxWidth: 180 }}>
              <label>Fine <span className="muted">(opz., eventi "dal–al")</span></label>
              <input className="input" type="date" value={form.event_end_date}
                     min={form.event_date || undefined}
                     onChange={e => setForm({ ...form, event_end_date: e.target.value })} />
            </div>
            <div className="field" style={{ flex: "1 1 260px" }}>
              <label>Titolo</label>
              <input className="input" placeholder="es. Lancio razzo test AST" value={form.title}
                     onChange={e => setForm({ ...form, title: e.target.value })}
                     onKeyDown={e => e.key === "Enter" && canSave && save()} />
            </div>
            <div className="field" style={{ maxWidth: 200 }}>
              <label>Ticker <span className="muted">(opz., anche più di uno)</span></label>
              <input className="input mono" placeholder="ASTS, T, VZ" value={form.symbol}
                     onChange={e => setForm({ ...form, symbol: e.target.value.toUpperCase() })} />
            </div>
          </div>

          <div className="field" style={{ marginTop: 12 }}>
            <label>Categoria</label>
            <div className="news-cat-chips">
              {cats.map(c => (
                <button key={c} type="button"
                        className={"news-chip" + (form.category === c ? " active" : "")}
                        onClick={() => setForm({ ...form, category: c })}>
                  {(_CAT_EMOJI[c] || "•")} {c}
                </button>
              ))}
            </div>
          </div>

          <div className="field" style={{ marginTop: 12 }}>
            <label>Nota <span className="muted">(opzionale — vai a capo liberamente, usa "-" per gli elenchi)</span></label>
            <textarea className="input news-note-input" rows={4}
                      placeholder={"Dettaglio o contesto, es.:\n- orario evento\n- cosa guardare\n- livelli chiave"}
                      value={form.note}
                      onChange={e => setForm({ ...form, note: e.target.value })} />
          </div>

          <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
            <button className="btn btn-primary" onClick={save} disabled={!canSave}>
              {saving ? "Salvataggio…" : editId != null ? "Salva modifiche" : "Salva evento"}
            </button>
            {editId != null &&
              <button className="btn btn-ghost" onClick={closeForm}>Annulla</button>}
          </div>
        </div>
        )}

        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", margin: "16px 4px 8px" }}>
          <span className="muted" style={{ fontSize: 13 }}>
            {visible.length} {visible.length === 1 ? "evento" : "eventi"} {showPast ? "" : "in arrivo"}
          </span>
          <button className="btn btn-sm btn-ghost" onClick={() => setShowPast(!showPast)}>
            {showPast ? "Solo futuri" : "Mostra anche passati"}
          </button>
        </div>

        {err && <div className="card">Errore: {err}</div>}
        {days.length === 0 && !err &&
          <div className="card muted">Nessun evento. Aggiungi il primo qui sopra (es. «Lancio iPhone 30» il 25).</div>}

        {days.map(day => {
          const away = _daysAway(day);
          const past = away < 0;
          // giorno passato ma con un evento multi-giorno non ancora finito → "in corso"
          const ongoing = past && byDay[day].some(e => e.event_end_date && _daysAway(e.event_end_date) >= 0);
          const badge = past ? (ongoing ? "in corso" : "")
                             : away === 0 ? "oggi" : away === 1 ? "domani" : `tra ${away}g`;
          return (
            <div className="card news-day-card" key={day} style={{ opacity: past && !ongoing ? 0.55 : 1 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <b>{_fmtDay(day)}</b>
                {badge && <span className="badge" style={{ background: (away <= 1 || ongoing) ? "var(--accent, #f59e0b)" : "var(--border)" }}>{badge}</span>}
              </div>
              {byDay[day].map(ev => (
                <div key={ev.id} style={{ display: "flex", gap: 8, alignItems: "flex-start", marginTop: 8 }}>
                  <span style={{ fontSize: 18 }}>{_CAT_EMOJI[ev.category] || "•"}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div>
                      <b>{ev.title}</b>
                      {ev.event_end_date &&
                        <span className="badge" style={{ marginLeft: 6, background: "var(--border)" }}>
                          → {_fmtArtDate(ev.event_end_date)}
                        </span>}
                      {(ev.symbol || "").split(",").filter(Boolean).map(s =>
                        <span key={s} className="badge mono" style={{ marginLeft: 6 }}>{s}</span>)}
                    </div>
                    {ev.note && <div className="muted news-note" style={{ fontSize: 12 }}>{ev.note}</div>}
                  </div>
                  <button className="btn btn-sm btn-ghost news-del" title="Modifica"
                          onClick={() => startEdit(ev)}>✎</button>
                  <button className="btn btn-sm btn-ghost news-del" title="Elimina"
                          onClick={() => setConfirmDel(ev)}>✕</button>
                </div>
              ))}
            </div>
          );
        })}

        <div className="muted" style={{ fontSize: 12, marginTop: 10 }}>
          Agenda manuale dei catalizzatori che vuoi seguire (lanci, prodotti, IPO, eventi macro).
          Ogni lunedì mattina ricevi su Telegram il riepilogo della settimana, + un promemoria il giorno prima.
        </div>

        {confirmDel && (
          <div className="wl-modal-backdrop" onClick={() => setConfirmDel(null)}>
            <div className="wl-modal card" onClick={e => e.stopPropagation()}>
              <div className="wl-modal-title">Eliminare questo evento?</div>
              <div className="wl-modal-text">
                {(_CAT_EMOJI[confirmDel.category] || "•")} <b>{confirmDel.title}</b>
                {" — "}{_fmtDay(confirmDel.event_date)}. L'azione non è reversibile.
              </div>
              <div className="wl-modal-actions">
                <button className="btn btn-sm btn-ghost" onClick={() => setConfirmDel(null)}>Annulla</button>
                <button className="btn btn-sm btn-danger" onClick={doDelete}>Elimina</button>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  };
})();
