/* =========================================================
   ANTARES — App shell + Login
   ========================================================= */

const { useState: useS, useEffect: useE } = React;
const { Cruscotto, Fatture, Collaboratori, Cespiti, Icon } = window.AntaresScreens1;
const { Margini, Riclassificato, StatoPatrimoniale, Tesoreria, Scadenze } = window.AntaresScreens2;
const { Preventivi, Statistiche, Anagrafica, CalendarioAttrezzatura, CaricoCollaboratori } = window.AntaresScreens3;

const TABS = [
  { id: "cruscotto",       label: "Cruscotto",              icon: "home"  },
  { id: "preventivi",      label: "Preventivi",             icon: "file"  },
  { id: "fatture",         label: "Fatture",                icon: "doc"   },
  { id: "tesoreria",       label: "Tesoreria",              icon: "cash"  },
  { id: "scadenze",        label: "Scadenze",               icon: "clock" },
  { id: "collaboratori",   label: "Collaboratori",          icon: "users" },
  { id: "carico-collab",   label: "Carico collaboratori",   icon: "users" },
  { id: "cespiti",         label: "Cespiti",                icon: "box"   },
  { id: "calendario-attr", label: "Calendario attrezzatura",icon: "cal"   },
  { id: "margini",         label: "Margini progetto",       icon: "chart" },
  { id: "anagrafica",      label: "Anagrafica",             icon: "users" },
  { id: "statistiche",     label: "Statistiche",            icon: "chart" },
  { id: "riclassificato",  label: "Conto Economico",        icon: "file"  },
  { id: "patrimoniale",    label: "Stato Patrimoniale",     icon: "file"  },
];

/* ---------- Theme toggle (riusabile) ---------- */
function ThemeToggle({ theme, setTheme, className = "theme-toggle" }) {
  return (
    <button
      className={className}
      onClick={() => setTheme(theme === "light" ? "dark" : "light")}
      aria-label={theme === "light" ? "Passa al tema scuro" : "Passa al tema chiaro"}
      title={theme === "light" ? "Tema chiaro" : "Tema scuro"}
    >
      {theme === "light" ? (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="4" />
          <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
        </svg>
      ) : (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z" />
        </svg>
      )}
    </button>
  );
}

/* ============================================================
   LOGIN — Supabase Auth (email + password reali)
   ============================================================ */
function Login({ theme, setTheme }) {
  const [email, setEmail] = useS("");
  const [pwd, setPwd]     = useS("");
  const [err, setErr]     = useS("");
  const [info, setInfo]   = useS("");
  const [loading, setLoading] = useS(false);
  const [mode, setMode]   = useS("login"); // login | forgot

  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setInfo("");
    if (!email.trim() || !pwd) { setErr("Email e password obbligatorie"); return; }
    setLoading(true);
    const { error } = await window.AntaresAuth.signIn(email.trim(), pwd);
    setLoading(false);
    if (error) {
      setErr(error.message === "Invalid login credentials"
        ? "Email o password non corrette"
        : error.message);
    }
    // su success, onAuthChange in App() reagisce automaticamente
  };

  const sendReset = async (e) => {
    e.preventDefault();
    setErr(""); setInfo("");
    if (!email.trim()) { setErr("Inserisci la tua email"); return; }
    setLoading(true);
    const { error } = await window.AntaresAuth.requestPasswordReset(email.trim());
    setLoading(false);
    if (error) setErr(error.message);
    else setInfo("Ti abbiamo inviato un'email con il link per reimpostare la password.");
  };

  return (
    <div className="login-screen">
      <div className="login-bg" />
      <div className="login-theme-toggle">
        <ThemeToggle theme={theme} setTheme={setTheme} />
      </div>

      <div className="login-card">
        <div className="login-logo-frame">
          <div className="login-logo-bg">
            <img src="assets/antares-logo.png" alt="Antares Film" />
          </div>
        </div>

        <h1 className="login-title">Antares Controllo</h1>
        <div className="login-sub">Controllo di gestione · Antares Film S.r.l.</div>

        <form className="login-form" onSubmit={mode === "login" ? submit : sendReset} autoComplete="on">
          {err  && <div className="login-error">{err}</div>}
          {info && <div className="login-error" style={{ background: "rgba(0,180,120,.12)", borderColor: "rgba(0,180,120,.4)", color: "var(--text)" }}>{info}</div>}

          <div className="login-input-wrap">
            <span className="lock">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z" />
                <path d="M22 6l-10 7L2 6" />
              </svg>
            </span>
            <input
              className="login-input"
              type="email"
              placeholder="Email"
              value={email}
              onChange={(e) => { setEmail(e.target.value); setErr(""); }}
              autoComplete="username"
              autoFocus
            />
          </div>

          {mode === "login" && (
            <div className="login-input-wrap">
              <span className="lock">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
                  <path d="M7 11V7a5 5 0 0110 0v4" />
                </svg>
              </span>
              <input
                className="login-input"
                type="password"
                placeholder="Password"
                value={pwd}
                onChange={(e) => { setPwd(e.target.value); setErr(""); }}
                autoComplete="current-password"
              />
            </div>
          )}

          <button type="submit" className="login-btn" disabled={loading}>
            {loading ? "Attendi…" : (mode === "login" ? "Entra" : "Invia link di reset")}
            {!loading && (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14M13 5l7 7-7 7" />
              </svg>
            )}
          </button>

          <button
            type="button"
            onClick={() => { setMode(mode === "login" ? "forgot" : "login"); setErr(""); setInfo(""); }}
            style={{ background: "none", border: 0, color: "var(--muted)", cursor: "pointer", fontSize: 13, marginTop: 4 }}
          >
            {mode === "login" ? "Password dimenticata?" : "← Torna al login"}
          </button>
        </form>

        <div className="login-meta">
          <span><span className="dot" /> Solo utenti invitati</span>
          <span>v1.0</span>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   RESET PASSWORD — quando l'utente clicca il link dall'email
   ============================================================ */
function ResetPassword({ onDone, theme, setTheme }) {
  const [pwd, setPwd]   = useS("");
  const [pwd2, setPwd2] = useS("");
  const [err, setErr]   = useS("");
  const [loading, setLoading] = useS(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    if (pwd.length < 8) { setErr("La password deve essere di almeno 8 caratteri"); return; }
    if (pwd !== pwd2)    { setErr("Le password non coincidono"); return; }
    setLoading(true);
    const { error } = await window.AntaresAuth.updatePassword(pwd);
    setLoading(false);
    if (error) setErr(error.message);
    else onDone();
  };

  return (
    <div className="login-screen">
      <div className="login-bg" />
      <div className="login-theme-toggle"><ThemeToggle theme={theme} setTheme={setTheme} /></div>
      <div className="login-card">
        <h1 className="login-title">Imposta una nuova password</h1>
        <div className="login-sub">Antares Controllo</div>
        <form className="login-form" onSubmit={submit} autoComplete="off">
          {err && <div className="login-error">{err}</div>}
          <div className="login-input-wrap">
            <input className="login-input" type="password" placeholder="Nuova password (min 8)"
              value={pwd} onChange={(e) => setPwd(e.target.value)} autoFocus />
          </div>
          <div className="login-input-wrap">
            <input className="login-input" type="password" placeholder="Ripeti password"
              value={pwd2} onChange={(e) => setPwd2(e.target.value)} />
          </div>
          <button type="submit" className="login-btn" disabled={loading}>
            {loading ? "Salvo…" : "Salva e accedi"}
          </button>
        </form>
      </div>
    </div>
  );
}

/* ============================================================
   APP SHELL
   ============================================================ */
function Shell({ onLogout, theme, setTheme, profile }) {
  const [tab, setTab] = useS(() => localStorage.getItem("antares.tab") || "cruscotto");
  const [year, setYear] = useS("2026");
  const [drawer, setDrawer] = useS(false);
  const [userMenu, setUserMenu] = useS(false);
  const [showPwdModal, setShowPwdModal] = useS(false);
  const [showProgModal, setShowProgModal] = useS(false);
  const [showInviteModal, setShowInviteModal] = useS(false);
  const [, setDataV] = useS(0);
  const isAdmin = profile?.ruolo === "admin";

  // re-render quando il data store si aggiorna (insert/update/delete)
  useE(() => {
    const h = () => setDataV(v => v + 1);
    window.addEventListener("antares:data", h);
    return () => window.removeEventListener("antares:data", h);
  }, []);

  const displayName = (profile?.nome || (profile?.email || "").split("@")[0] || "Utente");
  const initial = (displayName[0] || "U").toUpperCase();

  // close user menu on outside click
  useE(() => {
    if (!userMenu) return;
    const h = (e) => { if (!e.target.closest(".user-chip-wrap")) setUserMenu(false); };
    document.addEventListener("click", h);
    return () => document.removeEventListener("click", h);
  }, [userMenu]);

  useE(() => {
    localStorage.setItem("antares.tab", tab);
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [tab]);

  const navigate = (id) => { setTab(id); setDrawer(false); };

  const screen = (() => {
    switch (tab) {
      case "cruscotto":       return <Cruscotto onNavigate={navigate} />;
      case "preventivi":      return <Preventivi />;
      case "fatture":         return <Fatture />;
      case "collaboratori":   return <Collaboratori />;
      case "carico-collab":   return <CaricoCollaboratori />;
      case "cespiti":         return <Cespiti />;
      case "calendario-attr": return <CalendarioAttrezzatura />;
      case "margini":         return <Margini />;
      case "anagrafica":      return <Anagrafica />;
      case "statistiche":     return <Statistiche />;
      case "riclassificato":  return <Riclassificato />;
      case "patrimoniale":    return <StatoPatrimoniale />;
      case "tesoreria":       return <Tesoreria />;
      case "scadenze":        return <Scadenze />;
      default: return <Cruscotto onNavigate={navigate} />;
    }
  })();

  return (
    <div className="app">
      {/* TOP BAR */}
      <header className="topbar">
        <div className="topbar-inner">
          <button className="menu-btn" onClick={() => setDrawer(true)} aria-label="Menu">
            <Icon name="menu" />
          </button>
          <div className="brand">
            <div className="brand-mark">A</div>
            <div>
              <div>Antares Film</div>
              <div className="brand-sub">CONTROLLO DI GESTIONE</div>
            </div>
          </div>

          <div className="year-selector">
            <button className={year === "2024" ? "active" : ""} onClick={() => setYear("2024")}>2024</button>
            <button className={year === "2025" ? "active" : ""} onClick={() => setYear("2025")}>2025</button>
            <button className={year === "2026" ? "active" : ""} onClick={() => setYear("2026")}>2026</button>
          </div>

          <ThemeToggle theme={theme} setTheme={setTheme} />
          <div className="user-chip-wrap" style={{ position: "relative" }}>
            <button
              type="button"
              className="user-chip"
              onClick={() => setUserMenu(v => !v)}
              title={profile?.email}
              style={{ cursor: "pointer", border: 0, background: "inherit", font: "inherit", color: "inherit" }}
            >
              <div className="avatar">{initial}</div>
              <span>{displayName}{profile?.ruolo === "admin" ? " · admin" : ""}</span>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 4, opacity: .6 }}>
                <path d="M6 9l6 6 6-6" />
              </svg>
            </button>
            {userMenu && (
              <div
                role="menu"
                style={{
                  position: "absolute", right: 0, top: "calc(100% + 6px)",
                  background: "var(--surface, #fff)", border: "1px solid var(--border, #e5e7eb)",
                  borderRadius: 10, boxShadow: "0 8px 24px rgba(0,0,0,.12)",
                  minWidth: 220, padding: 6, zIndex: 100,
                }}
              >
                <div style={{ padding: "8px 10px", fontSize: 12, color: "var(--muted)", borderBottom: "1px solid var(--border, #e5e7eb)" }}>
                  {profile?.email}
                </div>
                <button
                  type="button"
                  onClick={() => { setUserMenu(false); setShowProgModal(true); }}
                  style={{ display: "block", width: "100%", textAlign: "left", padding: "9px 10px", background: "none", border: 0, cursor: "pointer", borderRadius: 6, font: "inherit", color: "inherit" }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2, #f3f4f6)"}
                  onMouseLeave={e => e.currentTarget.style.background = "none"}
                >
                  Gestisci progetti
                </button>
                {isAdmin && (
                  <button
                    type="button"
                    onClick={() => { setUserMenu(false); setShowInviteModal(true); }}
                    style={{ display: "block", width: "100%", textAlign: "left", padding: "9px 10px", background: "none", border: 0, cursor: "pointer", borderRadius: 6, font: "inherit", color: "inherit" }}
                    onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2, #f3f4f6)"}
                    onMouseLeave={e => e.currentTarget.style.background = "none"}
                  >
                    Invita utente…
                  </button>
                )}
                <button
                  type="button"
                  onClick={async () => {
                    setUserMenu(false);
                    if (!confirm("Invia ora una mail con il digest delle scadenze a tutti gli admin?")) return;
                    try {
                      const r = await window.AntaresAuth.sendScadenzeDigest(false);
                      if (r.error) { alert("Errore: " + r.error.message); return; }
                      const d = r.data;
                      if (d?.message) { alert(d.message); return; }
                      alert(`✓ Digest inviato a ${d?.sent || 0}/${d?.total || 0} admin\n\nScadenze: ${d?.scadenze || 0}\nIncassi attesi: ${d?.incassi || 0}`);
                    } catch (e) {
                      alert("Errore: " + (e.message || e));
                    }
                  }}
                  style={{ display: "block", width: "100%", textAlign: "left", padding: "9px 10px", background: "none", border: 0, cursor: "pointer", borderRadius: 6, font: "inherit", color: "inherit" }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2, #f3f4f6)"}
                  onMouseLeave={e => e.currentTarget.style.background = "none"}
                >
                  📧 Invia digest scadenze ora
                </button>
                <div style={{ height: 1, background: "var(--border, #e5e7eb)", margin: "4px 0" }} />
                <button
                  type="button"
                  onClick={async () => {
                    setUserMenu(false);
                    try {
                      if (!window.AntaresBackup) {
                        alert("Modulo backup non caricato. Ricarica la pagina (⌘+Shift+R).");
                        return;
                      }
                      const r = await window.AntaresBackup.esportaBackup();
                      if (!r) return;
                      const msg = r.downloaded
                        ? `✓ Backup scaricato\n\nFile: ${r.fname}\nDimensione: ${r.sizeKB} KB`
                        : `Backup pronto ma il download diretto non è riuscito — usa la finestra di copia.`;
                      alert(msg + (r.errori?.length ? "\n\nAvvisi:\n" + r.errori.join("\n") : ""));
                    } catch (e) {
                      alert("Errore export: " + (e.message || e));
                    }
                  }}
                  style={{ display: "block", width: "100%", textAlign: "left", padding: "9px 10px", background: "none", border: 0, cursor: "pointer", borderRadius: 6, font: "inherit", color: "inherit" }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2, #f3f4f6)"}
                  onMouseLeave={e => e.currentTarget.style.background = "none"}
                >
                  ⬇︎ Esporta backup JSON
                </button>
                <button
                  type="button"
                  onClick={() => {
                    setUserMenu(false);
                    const input = document.createElement("input");
                    input.type = "file"; input.accept = "application/json,.json";
                    input.onchange = async (e) => {
                      const file = e.target.files?.[0];
                      if (!file) return;
                      if (!confirm("Importare il backup? Le righe con lo stesso ID verranno sovrascritte. I dati esistenti non in backup NON saranno cancellati.")) return;
                      try {
                        const txt = await file.text();
                        const rep = await window.AntaresBackup.importaBackup(txt);
                        const okMsg = Object.entries(rep.ok).map(([t, n]) => `${t}: ${n}`).join("\n");
                        const errMsg = Object.entries(rep.errori).map(([t, m]) => `${t}: ${m}`).join("\n");
                        alert("Import completato.\n\nImportate:\n" + (okMsg || "—") + (errMsg ? "\n\nErrori:\n" + errMsg : ""));
                        await window.AntaresStore.hydrate();
                      } catch (e) {
                        alert("Errore import: " + (e.message || e));
                      }
                    };
                    input.click();
                  }}
                  style={{ display: "block", width: "100%", textAlign: "left", padding: "9px 10px", background: "none", border: 0, cursor: "pointer", borderRadius: 6, font: "inherit", color: "inherit" }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2, #f3f4f6)"}
                  onMouseLeave={e => e.currentTarget.style.background = "none"}
                >
                  ⬆︎ Importa backup JSON
                </button>
                <div style={{ height: 1, background: "var(--border, #e5e7eb)", margin: "4px 0" }} />
                <button
                  type="button"
                  onClick={() => { setUserMenu(false); setShowPwdModal(true); }}
                  style={{ display: "block", width: "100%", textAlign: "left", padding: "9px 10px", background: "none", border: 0, cursor: "pointer", borderRadius: 6, font: "inherit", color: "inherit" }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2, #f3f4f6)"}
                  onMouseLeave={e => e.currentTarget.style.background = "none"}
                >
                  Cambia password
                </button>
                <button
                  type="button"
                  onClick={() => { setUserMenu(false); onLogout(); }}
                  style={{ display: "block", width: "100%", textAlign: "left", padding: "9px 10px", background: "none", border: 0, cursor: "pointer", borderRadius: 6, font: "inherit", color: "var(--danger, #c0392b)" }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2, #f3f4f6)"}
                  onMouseLeave={e => e.currentTarget.style.background = "none"}
                >
                  Esci
                </button>
              </div>
            )}
          </div>
        </div>
      </header>

      {/* NAV TABS (desktop) */}
      <nav className="nav">
        <div className="nav-inner">
          {TABS.map(t => (
            <button
              key={t.id}
              className={"nav-tab" + (tab === t.id ? " active" : "")}
              onClick={() => navigate(t.id)}
            >
              <Icon name={t.icon} size={15} />
              {t.label}
              {t.badge && <span className="tab-badge">{t.badge}</span>}
            </button>
          ))}
        </div>
      </nav>

      {/* DRAWER (mobile) */}
      <div className={"drawer-backdrop" + (drawer ? " open" : "")} onClick={() => setDrawer(false)} />
      <aside className={"drawer" + (drawer ? " open" : "")}>
        <div className="drawer-head">
          <div className="brand">
            <div className="brand-mark">A</div>
            <div className="serif" style={{ fontSize: 16 }}>Antares Film</div>
          </div>
          <button className="btn btn-icon ghost" onClick={() => setDrawer(false)}><Icon name="x" /></button>
        </div>
        <div className="drawer-list">
          {TABS.map(t => (
            <button key={t.id} className={"drawer-item" + (tab === t.id ? " active" : "")} onClick={() => navigate(t.id)}>
              <Icon name={t.icon} />
              <span style={{ flex: 1 }}>{t.label}</span>
              {t.badge && <span className="tab-badge">{t.badge}</span>}
            </button>
          ))}
        </div>
        <div className="drawer-footer">
          <button className="logout" onClick={onLogout}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9" />
            </svg>
            Esci · {displayName}
          </button>
          <div style={{ fontSize: 12, color: "var(--muted)" }}>
            Antares Film S.r.l. · Esercizio {year}
          </div>
        </div>
      </aside>

      {/* MAIN */}
      <main className="main">
        {screen}
      </main>

      {showPwdModal && <ChangePasswordModal onClose={() => setShowPwdModal(false)} />}
      {showProgModal && <ProgettiModal onClose={() => setShowProgModal(false)} />}
      {showInviteModal && <InviteUserModal onClose={() => setShowInviteModal(false)} />}
    </div>
  );
}

/* ---------- modale invito utente (solo admin) ---------- */
function InviteUserModal({ onClose }) {
  const [email, setEmail] = useS("");
  const [ruolo, setRuolo] = useS("collaboratore");
  const [busy, setBusy]   = useS(false);
  const [err, setErr]     = useS("");
  const [ok, setOk]       = useS(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    if (!email.trim()) { setErr("Email obbligatoria"); return; }
    setBusy(true);
    const res = await window.AntaresAuth.inviteUser(email.trim().toLowerCase(), ruolo);
    setBusy(false);
    if (res.error) { setErr(res.error.message || "Errore invio invito"); return; }
    setOk(true);
    setTimeout(onClose, 2000);
  };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.4)", zIndex: 200, display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: "var(--surface, #fff)", borderRadius: 14, padding: 24, width: "100%", maxWidth: 420, boxShadow: "0 20px 60px rgba(0,0,0,.25)" }}>
        <h3 style={{ margin: 0, marginBottom: 6, fontFamily: "Playfair Display, serif", fontSize: 22 }}>Invita un utente</h3>
        <p style={{ margin: 0, marginBottom: 16, fontSize: 13, color: "var(--muted)" }}>
          L'utente riceverà via email un link per impostare la password e accedere.
        </p>
        {ok ? (
          <div className="login-error" style={{ background: "rgba(0,180,120,.12)", borderColor: "rgba(0,180,120,.4)", color: "var(--text)" }}>
            ✓ Invito inviato a <strong>{email}</strong>
          </div>
        ) : (
          <form onSubmit={submit} autoComplete="off">
            {err && <div className="login-error" style={{ marginBottom: 10 }}>{err}</div>}
            <div className="login-input-wrap" style={{ marginBottom: 10 }}>
              <input className="login-input" type="email" placeholder="email@esempio.it" value={email} onChange={e => setEmail(e.target.value)} autoFocus />
            </div>
            <div style={{ marginBottom: 14 }}>
              <label className="label">Ruolo iniziale</label>
              <select className="select" value={ruolo} onChange={e => setRuolo(e.target.value)} style={{ width: "100%" }}>
                <option value="collaboratore">Collaboratore (può vedere e modificare tutto)</option>
                <option value="ospite">Ospite (riservato, futuro: vista limitata)</option>
                <option value="admin">Admin (può a sua volta invitare altri)</option>
              </select>
            </div>
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
              <button type="button" onClick={onClose} style={{ padding: "9px 14px", borderRadius: 8, border: "1px solid var(--border, #e5e7eb)", background: "none", cursor: "pointer" }}>Annulla</button>
              <button type="submit" className="login-btn" style={{ flex: "0 0 auto", width: "auto", padding: "9px 16px" }} disabled={busy}>{busy ? "Invio…" : "Invia invito"}</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

/* ---------- modale gestione progetti ---------- */
function ProgettiModal({ onClose }) {
  const [list, setList] = useS(window.AntaresData.PROGETTI || []);
  const [editing, setEditing] = useS(null); // null = new
  const [id, setId]       = useS("");
  const [nome, setNome]   = useS("");
  const [linea, setLinea] = useS("Service");
  const [cliente, setCliente] = useS("");
  const [stato, setStato] = useS("in corso");
  const [dataInizio, setDataInizio] = useS("");
  const [dataFine, setDataFine]     = useS("");
  const [err, setErr]     = useS("");
  const [busy, setBusy]   = useS(false);
  // ricerca / filtri lista
  const [q, setQ]           = useS("");
  const [fAnno, setFAnno]   = useS("tutti");
  const [fLinea, setFLinea] = useS("tutte");
  const [fStato, setFStato] = useS("tutti");

  const reset = () => {
    setEditing(null); setId(""); setNome(""); setLinea("Service");
    setCliente(""); setStato("in corso"); setDataInizio(""); setDataFine(""); setErr("");
  };

  const startEdit = (p) => {
    setEditing(p.id); setId(p.id); setNome(p.nome);
    setLinea(p.linea || "Service");
    setCliente(p.cliente || "");
    setStato(p.stato || "in corso");
    setDataInizio(p.data_inizio || p._raw?.data_inizio || "");
    setDataFine(p.data_fine || p._raw?.data_fine || "");
    setErr("");
    window.scrollTo?.(0, 0);
  };

  const refresh = async () => {
    await window.AntaresStore.refresh("progetti");
    setList([...window.AntaresData.PROGETTI]);
  };

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    if (!id.trim() || !nome.trim()) { setErr("ID e Nome obbligatori"); return; }
    setBusy(true);
    try {
      const row = { id: id.trim(), nome: nome.trim(), linea, cliente: cliente.trim() || null, stato,
        data_inizio: dataInizio || null, data_fine: dataFine || null };
      let res;
      if (editing) res = await window.AntaresAPI.progetti.update(editing, row);
      else         res = await window.AntaresAPI.progetti.insert(row);
      if (res.error) { setErr(res.error.message); setBusy(false); return; }
      await refresh();
      reset();
    } finally { setBusy(false); }
  };

  const remove = async (pid) => {
    if (!confirm(`Eliminare il progetto "${pid}"?`)) return;
    setBusy(true);
    try {
      const res = await window.AntaresAPI.progetti.remove(pid);
      if (res.error) { setErr(res.error.message); return; }
      await refresh();
      if (editing === pid) reset();
    } finally { setBusy(false); }
  };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.4)", zIndex: 200, display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: "var(--surface, #fff)", borderRadius: 14, padding: 24, width: "100%", maxWidth: 720, maxHeight: "90vh", overflow: "auto", boxShadow: "0 20px 60px rgba(0,0,0,.25)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
          <h3 style={{ margin: 0, fontFamily: "Playfair Display, serif", fontSize: 22 }}>Gestione progetti</h3>
          <button onClick={onClose} style={{ background: "none", border: 0, fontSize: 22, cursor: "pointer", color: "var(--muted)" }}>×</button>
        </div>

        <form onSubmit={submit} style={{ display: "grid", gridTemplateColumns: "1fr 2fr 1fr 1fr", gap: 8, marginBottom: 14 }}>
          <input className="input" placeholder="ID (es. skate-ostia)" value={id} onChange={e => setId(e.target.value)} disabled={!!editing} />
          <input className="input" placeholder="Nome progetto" value={nome} onChange={e => setNome(e.target.value)} />
          <input className="input" placeholder="Cliente" value={cliente} onChange={e => setCliente(e.target.value)} />
          <select className="select" value={linea} onChange={e => setLinea(e.target.value)}>
            {(window.AntaresData.LINEE_BUSINESS || []).map(L => <option key={L}>{L}</option>)}
          </select>
          <select className="select" value={stato} onChange={e => setStato(e.target.value)} style={{ gridColumn: "1 / 2" }}>
            <option value="in corso">in corso</option>
            <option value="chiuso">chiuso</option>
            <option value="ricorrente">ricorrente</option>
          </select>
          <label style={{ gridColumn: "2 / 3", fontSize: 11, color: "var(--muted)" }}>Data inizio
            <input className="input" type="date" value={dataInizio || ""} onChange={e => setDataInizio(e.target.value)} />
          </label>
          <label style={{ gridColumn: "3 / 4", fontSize: 11, color: "var(--muted)" }}>Data fine
            <input className="input" type="date" value={dataFine || ""} onChange={e => setDataFine(e.target.value)} />
          </label>
          <div style={{ gridColumn: "1 / -1", display: "flex", gap: 8, justifyContent: "flex-end" }}>
            {editing && <button type="button" onClick={reset} className="btn ghost">Annulla modifica</button>}
            <button type="submit" className="login-btn" style={{ width: "auto", padding: "9px 16px" }} disabled={busy}>
              {busy ? "Salvo…" : (editing ? "Aggiorna" : "+ Aggiungi progetto")}
            </button>
          </div>
          {err && <div className="login-error" style={{ gridColumn: "1 / -1" }}>{err}</div>}
        </form>

        {(() => {
          const anni = [...new Set((list || []).map(p => p.anno).filter(Boolean))].sort((a, b) => b - a);
          const filtered = (list || []).filter(p => {
            if (fAnno !== "tutti" && String(p.anno) !== String(fAnno)) return false;
            if (fLinea !== "tutte" && p.linea !== fLinea) return false;
            if (fStato !== "tutti" && p.stato !== fStato) return false;
            if (q.trim()) {
              const s = (p.nome + " " + (p.cliente || "") + " " + p.id).toLowerCase();
              if (!s.includes(q.toLowerCase().trim())) return false;
            }
            return true;
          }).sort((a, b) => (b.anno || 0) - (a.anno || 0) || String(a.nome).localeCompare(String(b.nome)));
          return (
            <>
              <div className="row" style={{ gap: 8, marginBottom: 10, flexWrap: "wrap" }}>
                <input className="input" placeholder="🔎 Cerca per nome, cliente o ID…" value={q} onChange={e => setQ(e.target.value)} style={{ flex: "1 1 220px" }} />
                <select className="select" value={fAnno} onChange={e => setFAnno(e.target.value)} style={{ width: "auto" }}>
                  <option value="tutti">Tutti gli anni</option>
                  {anni.map(a => <option key={a} value={a}>{a}</option>)}
                </select>
                <select className="select" value={fLinea} onChange={e => setFLinea(e.target.value)} style={{ width: "auto" }}>
                  <option value="tutte">Tutte le linee</option>
                  {(window.AntaresData.LINEE_BUSINESS || []).map(L => <option key={L} value={L}>{L}</option>)}
                </select>
                <select className="select" value={fStato} onChange={e => setFStato(e.target.value)} style={{ width: "auto" }}>
                  <option value="tutti">Tutti gli stati</option>
                  <option value="in corso">in corso</option>
                  <option value="chiuso">chiuso</option>
                  <option value="ricorrente">ricorrente</option>
                </select>
              </div>
              <div className="muted" style={{ fontSize: 12, marginBottom: 6 }}>{filtered.length} di {(list || []).length} progetti</div>
              <table className="table" style={{ width: "100%", borderCollapse: "collapse" }}>
                <thead>
                  <tr><th>Anno</th><th>Nome</th><th>Cliente</th><th>Linea</th><th>Stato</th><th></th></tr>
                </thead>
                <tbody>
                  {filtered.length === 0 && (
                    <tr><td colSpan="6" style={{ padding: 20, textAlign: "center", color: "var(--muted)" }}>
                      {(list || []).length === 0 ? "Nessun progetto. Aggiungi il primo qui sopra." : "Nessun progetto coi filtri attuali."}
                    </td></tr>
                  )}
                  {filtered.map(p => (
                    <tr key={p.id}>
                      <td className="mono">{p.anno || "—"}</td>
                      <td><strong>{p.nome}</strong><div className="muted" style={{ fontSize: 11 }}><code>{p.id}</code></div></td>
                      <td>{p.cliente || "—"}</td>
                      <td>{p.linea}</td>
                      <td>{p.stato}</td>
                      <td style={{ textAlign: "right", whiteSpace: "nowrap" }}>
                        <button onClick={() => startEdit(p)} style={{ marginRight: 6, background: "none", border: "1px solid var(--border)", borderRadius: 6, padding: "4px 8px", cursor: "pointer" }}>Modifica</button>
                        <button onClick={() => remove(p.id)} style={{ background: "none", border: "1px solid var(--border)", borderRadius: 6, padding: "4px 8px", cursor: "pointer", color: "var(--danger, #c0392b)" }}>Elimina</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          );
        })()}
      </div>
    </div>
  );
}

/* ---------- modale cambio password (in-app) ---------- */
function ChangePasswordModal({ onClose }) {
  const [pwd, setPwd]   = useS("");
  const [pwd2, setPwd2] = useS("");
  const [err, setErr]   = useS("");
  const [ok, setOk]     = useS(false);
  const [loading, setLoading] = useS(false);

  const submit = async (e) => {
    e.preventDefault();
    setErr("");
    if (pwd.length < 8) { setErr("Minimo 8 caratteri"); return; }
    if (pwd !== pwd2)    { setErr("Le password non coincidono"); return; }
    setLoading(true);
    const { error } = await window.AntaresAuth.updatePassword(pwd);
    setLoading(false);
    if (error) setErr(error.message);
    else { setOk(true); setTimeout(onClose, 1200); }
  };

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.4)", zIndex: 200, display: "flex", alignItems: "center", justifyContent: "center", padding: 16 }}>
      <div onClick={e => e.stopPropagation()} style={{ background: "var(--surface, #fff)", borderRadius: 14, padding: 24, width: "100%", maxWidth: 380, boxShadow: "0 20px 60px rgba(0,0,0,.25)" }}>
        <h3 style={{ margin: 0, marginBottom: 6, fontFamily: "Playfair Display, serif", fontSize: 22 }}>Cambia password</h3>
        <p style={{ margin: 0, marginBottom: 16, fontSize: 13, color: "var(--muted)" }}>Imposta una nuova password per il tuo account.</p>
        {ok ? (
          <div className="login-error" style={{ background: "rgba(0,180,120,.12)", borderColor: "rgba(0,180,120,.4)", color: "var(--text)" }}>
            Password aggiornata.
          </div>
        ) : (
          <form onSubmit={submit} autoComplete="off">
            {err && <div className="login-error" style={{ marginBottom: 10 }}>{err}</div>}
            <div className="login-input-wrap" style={{ marginBottom: 10 }}>
              <input className="login-input" type="password" placeholder="Nuova password (min 8)" value={pwd} onChange={e => setPwd(e.target.value)} autoFocus />
            </div>
            <div className="login-input-wrap" style={{ marginBottom: 14 }}>
              <input className="login-input" type="password" placeholder="Ripeti password" value={pwd2} onChange={e => setPwd2(e.target.value)} />
            </div>
            <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
              <button type="button" onClick={onClose} style={{ padding: "9px 14px", borderRadius: 8, border: "1px solid var(--border, #e5e7eb)", background: "none", cursor: "pointer" }}>Annulla</button>
              <button type="submit" className="login-btn" style={{ flex: "0 0 auto", width: "auto", padding: "9px 16px" }} disabled={loading}>{loading ? "Salvo…" : "Salva"}</button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

/* ============================================================
   ROOT
   ============================================================ */
function App() {
  const [session, setSession] = useS(null);
  const [profile, setProfile] = useS(null);
  const [booting, setBooting] = useS(true);
  const [hydrating, setHydrating] = useS(false);
  const [recovering, setRecovering] = useS(false);
  const [theme, setTheme] = useS(() => localStorage.getItem("antares.theme") || "light");

  // hydrate dati live quando c'è sessione
  useE(() => {
    if (!session) return;
    let cancelled = false;
    setHydrating(true);
    window.AntaresStore.hydrate().finally(() => {
      if (cancelled) return;
      setHydrating(false);
      // Backup automatico su Storage: 1 volta per sessione, in background, non bloccante.
      // Se fallisce (es. bucket non ancora creato) logga soltanto: non disturba l'utente.
      try {
        if (!sessionStorage.getItem("antares.autobackup.done")) {
          sessionStorage.setItem("antares.autobackup.done", "1");
          setTimeout(() => {
            window.AntaresBackup?.backupToStorage?.()
              .then(r => { if (r && !r.ok) console.warn("[autobackup]", r.error); })
              .catch(e => console.warn("[autobackup]", e));
          }, 4000);
        }
      } catch (e) { console.warn("[autobackup] skip:", e); }
    });
    return () => { cancelled = true; };
  }, [session?.user?.id]);

  useE(() => {
    document.documentElement.setAttribute("data-theme", theme);
    localStorage.setItem("antares.theme", theme);
  }, [theme]);

  // bootstrap: leggi sessione esistente + ascolta cambi auth
  useE(() => {
    let mounted = true;
    (async () => {
      const s = await window.AntaresAuth.getSession();
      if (!mounted) return;
      setSession(s);
      if (s) setProfile(await window.AntaresAuth.getMyProfile());
      setBooting(false);
    })();

    // detect invite landing: ?invite=1 in URL means utente appena invitato
    const isInvited = new URLSearchParams(window.location.search).get("invite") === "1";

    const { data: sub } = window.AntaresAuth.onAuthChange(async (event, s) => {
      setSession(s);
      if (event === "PASSWORD_RECOVERY") setRecovering(true);
      // se l'utente arriva da invito appena confermato, deve impostare la password
      if (s && isInvited && event === "SIGNED_IN") setRecovering(true);
      if (s) setProfile(await window.AntaresAuth.getMyProfile());
      else   setProfile(null);
    });

    return () => { mounted = false; sub?.subscription?.unsubscribe?.(); };
  }, []);

  const logout = async () => {
    await window.AntaresAuth.signOut();
    // onAuthChange aggiorna session=null
  };

  if (booting) {
    return (
      <div className="login-screen">
        <div className="login-bg" />
        <div className="login-card" style={{ textAlign: "center" }}>
          <div style={{ fontSize: 14, color: "var(--muted)" }}>Carico…</div>
        </div>
      </div>
    );
  }

  if (recovering) {
    return <ResetPassword onDone={() => {
      setRecovering(false);
      // pulisci eventuali query string di flusso (?invite=1, ?reset=1)
      if (window.location.search) {
        window.history.replaceState({}, "", window.location.pathname);
      }
    }} theme={theme} setTheme={setTheme} />;
  }

  if (!session) {
    return <Login theme={theme} setTheme={setTheme} />;
  }

  if (hydrating) {
    return (
      <div className="login-screen">
        <div className="login-bg" />
        <div className="login-card" style={{ textAlign: "center" }}>
          <div style={{ fontSize: 14, color: "var(--muted)" }}>Carico dati…</div>
        </div>
      </div>
    );
  }

  return <Shell onLogout={logout} theme={theme} setTheme={setTheme} profile={profile} />;
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
