/* Settings — per-account module customization ========================
   Granular, grouped widget visibility (individual KPI tiles, charts,
   tables) + advertising-platform visibility, per account. Changes
   persist and reflect LIVE in the Overview + sidebar.
   RBAC: only super_admin + admin may edit (settings.manage).
=================================================================== */

/* Grouped, granular widgets. Each leaf id maps to a piece of the Overview. */
const WIDGET_GROUPS = [
  { id:'kpi', label:'KPI scoreboard', icon:'sparkles', tone:'#8351ff',
    desc:'Individual metric tiles at the top of the Overview.',
    items:[
      { id:'kpi_spend', label:'Amount spent', desc:'Hero spend tile + trend',        tone:'#8351ff' },
      { id:'kpi_roas',  label:'ROAS',         desc:'Return on ad spend',             tone:'#10b981' },
      { id:'kpi_cpa',   label:'Cost / result (CPA)', desc:'Average cost per result', tone:'#f59e0b' },
      { id:'kpi_cpc',   label:'Cost / click (CPC)',  desc:'Average cost per click',  tone:'#06b6d4' },
      { id:'kpi_ctr',   label:'Click-through rate',  desc:'CTR across campaigns',    tone:'#ec4899' },
    ]},
  { id:'charts', label:'Charts & insights', icon:'zap', tone:'#2f7bff',
    desc:'Trend, contribution and real-time signals.',
    items:[
      { id:'chart',        label:'Spend × ROAS chart', desc:'Daily spend vs return trend', tone:'#2f7bff' },
      { id:'platform_mix', label:'Platform mix',       desc:'Spend-share donut by platform', tone:'#8351ff' },
      { id:'anomalies',    label:'Anomalies feed',     desc:'Real-time alert cards (24h)',  tone:'#f59e0b' },
    ]},
  { id:'tables', label:'Tables & creative', icon:'columns', tone:'#10b981',
    desc:'Detailed campaign grid and creative gallery.',
    items:[
      { id:'campaign_table', label:'Campaign table',  desc:'Blended campaign grid',     tone:'#10b981' },
      { id:'creative',       label:'Creative preview', desc:'Top creative thumbnails',  tone:'#ec4899' },
    ]},
];
/* flattened list (for defaults, counts, lookups) */
const WIDGET_DEFS = WIDGET_GROUPS.flatMap(g=>g.items);
const WIDGET_BY_ID = Object.fromEntries(WIDGET_DEFS.map(w=>[w.id,w]));
const KPI_WIDGET_IDS = WIDGET_GROUPS.find(g=>g.id==='kpi').items.map(i=>i.id);

const TOGGLEABLE_PLATFORMS = ['meta','facebook','instagram','google','tiktok','snapchat','x','linkedin'];

function defaultModuleSettings(){
  const widgets = {}; WIDGET_DEFS.forEach(w=>widgets[w.id]=true);
  return { widgets, platforms: TOGGLEABLE_PLATFORMS.slice() };
}
const MODULE_LS = 'relay_module_settings_v1';
/* Platforms added after the first release. Per-account settings saved before a
   platform existed won't list it, so its sidebar tab stays hidden even once its
   feed goes live. This one-time migration enables newly-added platforms by
   default on existing saved accounts (users can still toggle them off in
   Settings). Bump the flag key when introducing another platform. */
const NEW_PLATFORMS = ['x','linkedin'];
const MODULE_MIGRATE_LS = 'relay_module_settings_migrated_platforms_v2';
function loadModuleSettings(){
  const all = loadLS(MODULE_LS, {});
  try {
    if (!loadLS(MODULE_MIGRATE_LS, false)){
      let changed = false;
      Object.keys(all).forEach(accId=>{
        const s = all[accId];
        if (s && Array.isArray(s.platforms)){
          NEW_PLATFORMS.forEach(pid=>{
            if (TOGGLEABLE_PLATFORMS.includes(pid) && !s.platforms.includes(pid)){
              s.platforms.push(pid); changed = true;
            }
          });
        }
      });
      if (changed) saveLS(MODULE_LS, all);
      saveLS(MODULE_MIGRATE_LS, true);
    }
  } catch(e){}
  return all;
}
/* Back-compat: older saved settings used a single `kpi` flag → expand it. */
function normalizeWidgets(w){
  const out = { ...w };
  if (out.kpi !== undefined){ KPI_WIDGET_IDS.forEach(id=>{ if(out[id]===undefined) out[id]=out.kpi; }); delete out.kpi; }
  return out;
}
function moduleSettingsFor(all, accountId){
  const base = all[accountId] || defaultModuleSettings();
  return { ...base, widgets: normalizeWidgets(base.widgets||{}) };
}

function SettingsView({ accountId, settings, onChange, canManage, currentUser }){
  const acc = ACCOUNTS.find(a=>a.id===accountId);
  const s = settings || defaultModuleSettings();
  const isOn = (id)=> s.widgets[id] !== false;
  const setWidget = (id,v)=> onChange({ ...s, widgets:{ ...s.widgets, [id]:v } });
  const setGroup = (group, v)=>{
    const next = { ...s.widgets };
    group.items.forEach(it=> next[it.id]=v);
    onChange({ ...s, widgets: next });
  };
  const setPlatform = (id)=>{
    const on = s.platforms.includes(id);
    onChange({ ...s, platforms: on ? s.platforms.filter(p=>p!==id) : [...s.platforms, id] });
  };
  const reset = ()=> onChange(defaultModuleSettings());
  const enabledCount = WIDGET_DEFS.filter(w=>isOn(w.id)).length;

  const lock = canManage ? '' : 'pointer-events-none opacity-50';

  return (
    <div className="space-y-4 max-w-[900px]">
      <div className="flex items-center gap-3">
        <span className="inline-flex items-center justify-center w-10 h-10 rounded-xl bg-ink-900 text-white dark:bg-white dark:text-ink-900"><Icon name="settings" size={22}/></span>
        <div className="flex-1">
          <h1 className="text-[20px] font-semibold tracking-tight leading-none">Settings</h1>
          <div className="text-[12px] text-ink-500 dark:text-ink-300 mt-1">Module visibility for <span className="font-semibold">{acc.name}</span> · saved per account</div>
        </div>
        {canManage && <Btn size="sm" variant="ghost" icon="arrow-down" onClick={reset}>Reset to defaults</Btn>}
      </div>

      {!canManage && (
        <div className="flex items-center gap-2 text-[12.5px] text-amber-700 dark:text-amber-300 bg-amber-50 dark:bg-amber-500/10 border border-amber-200 dark:border-amber-500/25 rounded-lg px-3 py-2">
          <Icon name="alert" size={14}/> View only — only an Admin or Super Admin can change module visibility.
        </div>
      )}

      <div>
        <div className="text-[11px] uppercase tracking-wide font-semibold text-ink-400 mb-2 px-1">Dashboard widgets</div>
        <div className="grid lg:grid-cols-2 gap-3">
          {WIDGET_GROUPS.map(group=>{
            const onCount = group.items.filter(it=>isOn(it.id)).length;
            const allOn = onCount===group.items.length;
            const noneOn = onCount===0;
            return (
              <Card key={group.id} className="rounded-2xl overflow-hidden">
                <div className="px-4 py-3 flex items-center gap-2.5 border-b border-ink-200 dark:border-white/10 bg-ink-50/50 dark:bg-white/[0.02]">
                  <span className="inline-flex items-center justify-center w-8 h-8 rounded-lg flex-shrink-0" style={{ background:`${group.tone}1a`, color:group.tone }}><Icon name={group.icon} size={16}/></span>
                  <div className="flex-1 min-w-0">
                    <div className="text-[13px] font-semibold flex items-center gap-2">{group.label}
                      <span className="text-[10.5px] font-mono font-normal text-ink-400">{onCount}/{group.items.length}</span>
                    </div>
                    <div className="text-[11px] text-ink-500 dark:text-ink-300 truncate">{group.desc}</div>
                  </div>
                  <button onClick={()=>setGroup(group, !allOn)} disabled={!canManage}
                    className={`text-[11px] font-medium px-2 h-7 rounded-md border transition flex-shrink-0 ${lock} ${noneOn?'border-ink-200 dark:border-white/10 text-ink-500 hover:bg-ink-100 dark:hover:bg-white/5':'border-accent-300 dark:border-accent-500/40 text-accent-700 dark:text-accent-200 bg-accent-50 dark:bg-accent-500/10'}`}>
                    {allOn?'Hide all':'Show all'}
                  </button>
                </div>
                <div>
                  {group.items.map(it=>(
                    <div key={it.id} className="px-4 py-2.5 flex items-center gap-3 border-b border-ink-100 dark:border-white/5 last:border-0">
                      <span className="w-1.5 h-1.5 rounded-full flex-shrink-0" style={{ background: isOn(it.id)?it.tone:'transparent', boxShadow: isOn(it.id)?'none':`inset 0 0 0 1.5px ${it.tone}55` }}/>
                      <div className="flex-1 min-w-0">
                        <div className="text-[13px] font-medium">{it.label}</div>
                        <div className="text-[11px] text-ink-500 dark:text-ink-300 truncate">{it.desc}</div>
                      </div>
                      <span className={lock}><Toggle checked={isOn(it.id)} onChange={v=>setWidget(it.id,v)} tone={it.tone}/></span>
                    </div>
                  ))}
                </div>
              </Card>
            );
          })}
        </div>
      </div>

      <div>
        <div className="text-[11px] uppercase tracking-wide font-semibold text-ink-400 mb-2 px-1">Advertising platforms</div>
        <Card className="rounded-2xl overflow-hidden">
          <div className="px-4 py-2.5 flex items-center justify-between border-b border-ink-200 dark:border-white/10 bg-ink-50/50 dark:bg-white/[0.02]">
            <div className="text-[12px] text-ink-500 dark:text-ink-300">Disabled platforms are hidden from the sidebar & tabs for this account.</div>
            <div className="flex items-center gap-1.5">
              <button onClick={()=>onChange({ ...s, platforms: TOGGLEABLE_PLATFORMS.slice() })} disabled={!canManage} className={`text-[11px] font-medium px-2 h-7 rounded-md border border-ink-200 dark:border-white/10 hover:bg-ink-100 dark:hover:bg-white/5 ${lock}`}>All</button>
              <button onClick={()=>onChange({ ...s, platforms: [] })} disabled={!canManage} className={`text-[11px] font-medium px-2 h-7 rounded-md border border-ink-200 dark:border-white/10 hover:bg-ink-100 dark:hover:bg-white/5 ${lock}`}>None</button>
            </div>
          </div>
          <div className="p-3 grid sm:grid-cols-2 gap-2">
            {TOGGLEABLE_PLATFORMS.map(pid=>{
              const p = PLATFORMS.find(x=>x.id===pid);
              const on = s.platforms.includes(pid);
              return (
                <button key={pid} disabled={!canManage} onClick={()=>setPlatform(pid)}
                  className={`flex items-center gap-2.5 px-3 py-2.5 rounded-xl border text-left transition ${on?'border-accent-300 bg-accent-50/60 dark:bg-accent-500/10 dark:border-accent-500/40':'border-ink-200 dark:border-white/10 opacity-60 hover:opacity-100'} ${canManage?'':'pointer-events-none'}`}>
                  <span className="inline-flex items-center justify-center w-7 h-7 text-ink-900 dark:text-white"><BrandIcon name={p.icon} size={20}/></span>
                  <span className="flex-1 text-[13px] font-medium">{p.label}</span>
                  <Toggle checked={on} onChange={()=>setPlatform(pid)} size="sm"/>
                </button>
              );
            })}
          </div>
        </Card>
      </div>

      <div className="text-[11.5px] text-ink-400 font-mono px-1">Saved per account · {enabledCount}/{WIDGET_DEFS.length} widgets · {s.platforms.length}/{TOGGLEABLE_PLATFORMS.length} platforms enabled</div>
    </div>
  );
}

Object.assign(window, { SettingsView, WIDGET_GROUPS, WIDGET_DEFS, WIDGET_BY_ID, KPI_WIDGET_IDS, TOGGLEABLE_PLATFORMS, defaultModuleSettings, loadModuleSettings, moduleSettingsFor, normalizeWidgets, MODULE_LS });
