/* ============================================================
   NOTIFICHE — preferenze utente + admin default
   ============================================================ */

const CAT_META = {
  prenotazioni: { label:'Prenotazioni', icon:'calendar', color:'var(--st-prenotato)' },
  noleggi:      { label:'Noleggi',      icon:'clock',    color:'#6c5ce7' },
  prodotti:     { label:'Prodotti',     icon:'boxes',    color:'var(--st-disponibile)' },
  clienti:      { label:'Clienti',      icon:'users',    color:'var(--red)' },
};

/* ---- Riga di preferenza (riusato da utente e admin) ----- */
function PrefRow({ event, pref, onChange, dark, showOnlyMy }) {
  const vp = useViewport();
  const Toggle = ({ active, onClick, label }) => (
    <button onClick={onClick} title={label}
      style={{ width:42, height:24, borderRadius:99, background: active?'var(--red)':'var(--line)',
        position:'relative', transition:'.18s', flexShrink:0, border:'none', cursor:'pointer' }}>
      <span style={{ position:'absolute', top:3, left: active?21:3, width:18, height:18, borderRadius:99,
        background:'#fff', transition:'.18s', boxShadow:'0 1px 2px rgba(0,0,0,.2)' }} />
    </button>
  );

  if (vp.isMobile) {
    return (
      <div style={{ padding:'14px 14px', borderBottom:'1px solid var(--line-2)' }}>
        <div style={{ marginBottom:10 }}>
          <div style={{ fontSize:13.5, fontWeight:700, color:'var(--ink)' }}>{event.label}</div>
          {event.description && <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>{event.description}</div>}
        </div>
        <div style={{ display:'flex', gap:14, alignItems:'center', flexWrap:'wrap' }}>
          <label style={{ display:'flex', alignItems:'center', gap:7, fontSize:12.5, fontWeight:600, color:'var(--ink-2)' }}>
            <Toggle active={pref.in_app} onClick={()=>onChange({ ...pref, in_app: !pref.in_app })} />
            In-app
          </label>
          <label style={{ display:'flex', alignItems:'center', gap:7, fontSize:12.5, fontWeight:600, color:'var(--ink-2)' }}>
            <Toggle active={pref.email} onClick={()=>onChange({ ...pref, email: !pref.email })} />
            Email
          </label>
          {showOnlyMy && event.supports_only_my && (
            <label style={{ display:'flex', alignItems:'center', gap:7, fontSize:12.5, fontWeight:600, color:'var(--ink-2)', cursor:'pointer' }}
              onClick={()=>onChange({ ...pref, only_my_actions: !pref.only_my_actions })}>
              <span style={{ width:18, height:18, borderRadius:5, flexShrink:0,
                border:'1.5px solid '+(pref.only_my_actions?'var(--red)':'var(--line)'),
                background: pref.only_my_actions?'var(--red)':'#fff',
                display:'flex', alignItems:'center', justifyContent:'center' }}>
                {pref.only_my_actions && <Icon name="check" size={11} stroke={3} style={{ color:'#fff' }} />}
              </span>
              Solo mie
            </label>
          )}
        </div>
      </div>
    );
  }

  return (
    <div style={{ display:'grid', gridTemplateColumns:'minmax(0,1fr) 70px 70px 100px', gap:14, alignItems:'center',
      padding:'13px 16px', borderBottom:'1px solid var(--line-2)' }}>
      <div style={{ minWidth:0 }}>
        <div style={{ fontSize:13.5, fontWeight:700, color:'var(--ink)' }}>{event.label}</div>
        {event.description && <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>{event.description}</div>}
      </div>
      <div style={{ display:'flex', justifyContent:'center' }}>
        <Toggle active={pref.in_app} onClick={()=>onChange({ ...pref, in_app: !pref.in_app })} label="In-app" />
      </div>
      <div style={{ display:'flex', justifyContent:'center' }}>
        <Toggle active={pref.email} onClick={()=>onChange({ ...pref, email: !pref.email })} label="Email" />
      </div>
      <div style={{ display:'flex', justifyContent:'center' }}>
        {showOnlyMy && event.supports_only_my ? (
          <label style={{ display:'flex', alignItems:'center', gap:6, cursor:'pointer' }} onClick={()=>onChange({ ...pref, only_my_actions: !pref.only_my_actions })}>
            <span style={{ width:18, height:18, borderRadius:5, flexShrink:0,
              border:'1.5px solid '+(pref.only_my_actions?'var(--red)':'var(--line)'),
              background: pref.only_my_actions?'var(--red)':'#fff',
              display:'flex', alignItems:'center', justifyContent:'center', transition:'.13s' }}>
              {pref.only_my_actions && <Icon name="check" size={11} stroke={3} style={{ color:'#fff' }} />}
            </span>
          </label>
        ) : (
          <span style={{ fontSize:11.5, color:'var(--ink-4)' }}>—</span>
        )}
      </div>
    </div>
  );
}

function PrefHeader({ showOnlyMy }) {
  const vp = useViewport();
  if (vp.isMobile) return null;
  return (
    <div style={{ display:'grid', gridTemplateColumns:'minmax(0,1fr) 70px 70px 100px', gap:14,
      padding:'12px 16px', background:'var(--surface-2)', borderBottom:'1px solid var(--line)',
      fontSize:11, fontWeight:800, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'.04em' }}>
      <span>Evento</span>
      <span style={{ textAlign:'center' }}>In-app</span>
      <span style={{ textAlign:'center' }}>Email</span>
      <span style={{ textAlign:'center' }}>{showOnlyMy ? 'Solo mie' : ''}</span>
    </div>
  );
}

/* ============================================================
   PREFERENZE UTENTE — pagina /notifiche
   ============================================================ */
function UserNotificationPrefs({ currentUser, toast }) {
  const vp = useViewport();
  const [eventTypes, setEventTypes] = useState([]);
  const [prefsMap, setPrefsMap] = useState({}); // event_type → pref
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [confirm, setConfirm] = useState(false);

  useEffect(() => {
    (async () => {
      const [types, prefs] = await Promise.all([
        window.LogAPI.listEventTypes(),
        window.LogAPI.getMyPreferences(),
      ]);
      setEventTypes(types);
      const map = {};
      prefs.forEach(p => { map[p.event_type] = p; });
      setPrefsMap(map);
      setLoading(false);
    })();
  }, []);

  const updatePref = async (eventType, newPref) => {
    setPrefsMap(prev => ({ ...prev, [eventType]: { ...newPref, _source:'user', is_default_modified:true } }));
    setSaving(true);
    const ok = await window.LogAPI.setMyPreference(eventType, newPref);
    setSaving(false);
    if (!ok) toast('Errore salvataggio preferenza');
  };

  const resetAll = async () => {
    setSaving(true);
    const ok = await window.LogAPI.resetMyPreferences();
    if (!ok) { toast('Errore reset'); setSaving(false); return; }
    // Reload
    const prefs = await window.LogAPI.getMyPreferences();
    const map = {};
    prefs.forEach(p => { map[p.event_type] = p; });
    setPrefsMap(map);
    setSaving(false);
    setConfirm(false);
    toast('Impostazioni ripristinate ai default');
  };

  const personalized = Object.values(prefsMap).filter(p => p._source === 'user').length;
  const role = currentUser?.role || currentUser?.ruolo;

  // Raggruppa per categoria
  const byCat = {};
  eventTypes.forEach(e => { (byCat[e.category] ||= []).push(e); });
  const categories = Object.keys(byCat);

  return (
    <div className="scroll" style={{ flex:1, minWidth:0, overflowY:'auto', overflowX:'hidden', display:'flex', flexDirection:'column' }}>
      <div style={{ padding: vp?.isMobile?'14px 14px 12px':'22px 30px 14px', borderBottom:'1px solid var(--line)', background:'var(--surface)' }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', flexWrap:'wrap', gap:14 }}>
          <div style={{ minWidth:0, flex:1 }}>
            <h2 style={{ margin:0, fontFamily:'var(--font-display)', fontSize: vp?.isMobile?17:20, fontWeight:800 }}>Le tue notifiche</h2>
            <p style={{ margin:'4px 0 0', fontSize: vp?.isMobile?12.5:13.5, color:'var(--ink-3)' }}>
              Scegli per quali eventi vuoi essere avvisato e come (in-app, email, o entrambi).
              {role==='commerciale' && ' Con "Solo mie" ricevi notifiche soltanto per le tue prenotazioni.'}
            </p>
          </div>
          <Btn variant="ghost" icon="refresh" size={vp?.isMobile?'sm':'md'} onClick={()=>setConfirm(true)} disabled={personalized===0}>
            {vp?.isMobile ? 'Reset' : 'Ripristina default'}
          </Btn>
        </div>
        <div style={{ marginTop:12, display:'flex', alignItems:'center', gap:8, fontSize:12, color:'var(--ink-4)' }}>
          <span style={{ display:'inline-flex', alignItems:'center', gap:5 }}>
            <span style={{ width:8, height:8, borderRadius:99, background:'var(--red)' }} />
            {personalized} {personalized===1?'preferenza personalizzata':'preferenze personalizzate'}
          </span>
          {saving && <span style={{ color:'var(--ink-3)' }}>· salvataggio…</span>}
        </div>
      </div>

      <div style={{ padding: vp?.isMobile?'14px 12px 30px':'22px 30px 50px', maxWidth:920, width:'100%', margin:'0 auto' }}>
        {loading ? (
          <div style={{ padding:'60px 0', textAlign:'center', color:'var(--ink-3)' }}>Caricamento…</div>
        ) : categories.map(catKey => {
          const meta = CAT_META[catKey] || { label: catKey, icon: 'tag' };
          return (
            <div key={catKey} style={{ marginBottom:24, background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', overflow:'hidden', boxShadow:'var(--sh-1)' }}>
              <div style={{ padding:'15px 18px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', gap:10 }}>
                <span style={{ width:32, height:32, borderRadius:8, flexShrink:0, background: 'color-mix(in srgb, '+meta.color+' 14%, var(--surface))', color: meta.color, display:'flex', alignItems:'center', justifyContent:'center' }}>
                  <Icon name={meta.icon} size={18} />
                </span>
                <h3 style={{ margin:0, fontFamily:'var(--font-display)', fontSize:16, fontWeight:800 }}>{meta.label}</h3>
              </div>
              <PrefHeader showOnlyMy={role==='commerciale'} />
              {byCat[catKey].map(event => {
                const pref = prefsMap[event.event_type] || { in_app:false, email:false, only_my_actions:false };
                return (
                  <PrefRow key={event.event_type}
                    event={event}
                    pref={pref}
                    onChange={(p)=>updatePref(event.event_type, p)}
                    showOnlyMy={role==='commerciale'}
                  />
                );
              })}
            </div>
          );
        })}
      </div>

      {confirm && <ConfirmDialog title="Ripristinare i default?"
        message={<>Tutte le tue {personalized} preferenze personalizzate verranno cancellate e tornerai ai default per il tuo ruolo.</>}
        confirmLabel="Ripristina" onConfirm={resetAll} onClose={()=>setConfirm(false)} />}
    </div>
  );
}

/* ============================================================
   ADMIN — Default notifiche per ruolo
   ============================================================ */
function AdminNotificheDefault({ toast }) {
  const [eventTypes, setEventTypes] = useState([]);
  const [defaults, setDefaults] = useState({}); // role → event_type → pref
  const [activeRole, setActiveRole] = useState('commerciale');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [propagateConfirm, setPropagateConfirm] = useState(false);

  useEffect(() => {
    (async () => {
      const [types, defs] = await Promise.all([
        window.LogAPI.listEventTypes(),
        window.LogAPI.listDefaultPreferences(),
      ]);
      setEventTypes(types);
      const map = { commerciale:{}, backoffice:{}, admin:{} };
      defs.forEach(d => { (map[d.role] ||= {})[d.event_type] = d; });
      setDefaults(map);
      setLoading(false);
    })();
  }, []);

  const updateDefault = async (role, eventType, newPref) => {
    setDefaults(prev => ({
      ...prev,
      [role]: { ...(prev[role]||{}), [eventType]: { ...newPref, role, event_type: eventType } }
    }));
    setSaving(true);
    const ok = await window.LogAPI.setDefaultPreference(role, eventType, newPref);
    setSaving(false);
    if (!ok) toast('Errore salvataggio');
  };

  const propagateDefaults = async () => {
    // Cancella TUTTE le preferenze utente con is_default_modified=false
    // così tornano a ereditare dai default aggiornati.
    // In realtà più semplice: cancella TUTTE le righe non personalizzate.
    // Ma noi tracciamo is_default_modified solo quando l'utente modifica esplicitamente.
    // Quindi rimuovendo tutte le righe con is_default_modified=false applichiamo i nuovi default.
    const sb = window.DataAPI.client();
    if (!sb) { toast('Errore'); return; }
    const { error } = await sb.from('notification_preferences')
      .delete()
      .eq('is_default_modified', false);
    if (error) { toast('Errore propagazione: ' + error.message); return; }
    setPropagateConfirm(false);
    toast('Default propagati agli utenti non personalizzati');
  };

  const role = activeRole;
  const byCat = {};
  eventTypes.forEach(e => { (byCat[e.category] ||= []).push(e); });
  const categories = Object.keys(byCat);

  return (
    <>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:16, gap:16, flexWrap:'wrap' }}>
        <div>
          <h2 style={{ margin:0, fontFamily:'var(--font-display)', fontSize:19, fontWeight:800 }}>Default notifiche per ruolo</h2>
          <div style={{ fontSize:13, color:'var(--ink-3)', marginTop:2 }}>
            Imposta i default per ogni ruolo. Gli utenti possono personalizzare le proprie preferenze.
          </div>
        </div>
        <Btn icon="refresh" onClick={()=>setPropagateConfirm(true)}>Propaga ai non personalizzati</Btn>
      </div>

      {/* Tabs ruolo */}
      <div style={{ display:'flex', gap:8, marginBottom:18 }}>
        {[['commerciale','Commerciale'],['backoffice','Back Office'],['admin','Admin']].map(([k,l]) => {
          const active = activeRole===k;
          return (
            <button key={k} onClick={()=>setActiveRole(k)} style={{ display:'flex', alignItems:'center', gap:8, padding:'10px 18px',
              borderRadius:99, fontSize:13.5, fontWeight:700,
              border:'1.5px solid '+(active?RUOLI[k].color:'var(--line)'),
              background: active?RUOLI[k].color:'var(--surface)',
              color: active?'#fff':'var(--ink-2)' }}>
              <Avatar name={l} size={20} color={active?'rgba(255,255,255,.2)':RUOLI[k].color} /> {l}
            </button>
          );
        })}
      </div>

      {loading ? (
        <div style={{ padding:'60px 0', textAlign:'center', color:'var(--ink-3)' }}>Caricamento…</div>
      ) : categories.map(catKey => {
        const meta = CAT_META[catKey] || { label: catKey, icon: 'tag' };
        return (
          <div key={catKey} style={{ marginBottom:18, background:'var(--surface)', border:'1px solid var(--line)', borderRadius:'var(--r-lg)', overflow:'hidden', boxShadow:'var(--sh-1)' }}>
            <div style={{ padding:'13px 18px', borderBottom:'1px solid var(--line)', display:'flex', alignItems:'center', gap:10 }}>
              <span style={{ width:30, height:30, borderRadius:8, flexShrink:0, background: 'color-mix(in srgb, '+meta.color+' 14%, var(--surface))', color: meta.color, display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name={meta.icon} size={17} />
              </span>
              <h3 style={{ margin:0, fontFamily:'var(--font-display)', fontSize:15, fontWeight:800 }}>{meta.label}</h3>
            </div>
            <PrefHeader showOnlyMy={role==='commerciale'} />
            {byCat[catKey].map(event => {
              const pref = (defaults[role]||{})[event.event_type] || { in_app:false, email:false, only_my_actions:false };
              return (
                <PrefRow key={event.event_type}
                  event={event}
                  pref={pref}
                  onChange={(p)=>updateDefault(role, event.event_type, p)}
                  showOnlyMy={role==='commerciale'}
                />
              );
            })}
          </div>
        );
      })}
      {saving && <div style={{ position:'fixed', bottom:90, right:30, padding:'8px 14px', background:'var(--ink)', color:'#fff', borderRadius:99, fontSize:12, fontWeight:600 }}>Salvataggio…</div>}

      {propagateConfirm && <ConfirmDialog title="Propagare i default?"
        message={<>I default attuali verranno applicati a <b>tutti gli utenti che non hanno personalizzato</b> le proprie preferenze. Gli utenti che le hanno modificate restano com'erano.</>}
        confirmLabel="Propaga" onConfirm={propagateDefaults} onClose={()=>setPropagateConfirm(false)} />}
    </>
  );
}

Object.assign(window, { UserNotificationPrefs, AdminNotificheDefault });