/* Automations Drawer ================================================= */

const SCOPES = [
  { id:'overview', label:'All platforms' },
  { id:'meta',     label:'Meta' },
  { id:'google',   label:'Google Ads' },
  { id:'tiktok',   label:'TikTok' },
  { id:'snapchat', label:'Snapchat' },
  { id:'x',        label:'X' },
];

const OBJECTS = [
  { id:'campaign', label:'Campaign' },
  { id:'adset',    label:'Ad set' },
  { id:'keyword',  label:'Keyword' },
];

const METRICS = [
  { id:'cpa',   label:'CPA',          unit:'$',  format:'currency2' },
  { id:'roas',  label:'ROAS',         unit:'×',  format:'x' },
  { id:'spend', label:'Spend (24h)',  unit:'$',  format:'currency' },
  { id:'ctr',   label:'CTR',          unit:'%',  format:'pct' },
  { id:'cpc',   label:'CPC',          unit:'$',  format:'currency2' },
  { id:'freq',  label:'Frequency',    unit:'x',  format:'x' },
];

const OPS_RULE = ['>', '<', '≥', '≤', '='];

const ACTIONS = [
  { id:'pause',          label:'Pause it',          tone:'rose'   },
  { id:'enable',         label:'Enable it',         tone:'emerald'},
  { id:'reduce_budget',  label:'Reduce budget 25%', tone:'amber'  },
  { id:'increase_budget',label:'Increase budget 20%',tone:'sky'   },
  { id:'notify',         label:'Notify on Slack',   tone:'accent' },
];

function Seg({ value, onChange, opts, small }){
  return (
    <div className={`inline-flex rounded-lg bg-ink-100 dark:bg-white/5 p-0.5 ${small?'text-[11px]':'text-[12px]'}`}>
      {opts.map(o => (
        <button key={o.id||o} onClick={()=>onChange(o.id||o)}
          className={`px-2 ${small?'h-6':'h-7'} rounded-md font-medium transition
            ${(value===(o.id||o)) ? 'bg-white dark:bg-ink-800 shadow-sm text-ink-900 dark:text-white' : 'text-ink-500 dark:text-ink-300 hover:text-ink-800 dark:hover:text-white'}`}>
          {o.label||o}
        </button>
      ))}
    </div>
  );
}

function RuleCard({ rule, onChange, onDelete }){
  const r = rule;
  const upd = (patch) => onChange({ ...r, ...patch });
  const actionTone = (ACTIONS.find(a=>a.id===r.action)?.tone) || 'neutral';
  return (
    <div className={`rounded-xl border bg-white dark:bg-ink-900/60 transition ${r.enabled?'border-ink-200 dark:border-white/10':'border-ink-200/70 dark:border-white/5 opacity-65'}`}>
      <div className="px-4 pt-3 pb-2 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Toggle checked={r.enabled} onChange={(v)=>upd({enabled:v})} size="sm"/>
          <span className="text-[12px] font-medium text-ink-700 dark:text-ink-100">{r.enabled?'Active':'Paused'}</span>
          <Pill tone={actionTone==='rose'?'bad':actionTone==='emerald'?'good':actionTone==='amber'?'warn':actionTone==='sky'?'info':'accent'}>
            {ACTIONS.find(a=>a.id===r.action)?.label}
          </Pill>
        </div>
        <div className="flex items-center gap-1">
          <button onClick={onDelete} className="h-7 w-7 grid place-items-center rounded-lg hover:bg-rose-50 hover:text-rose-600 dark:hover:bg-rose-500/10 dark:hover:text-rose-300 text-ink-400">
            <Icon name="x" size={14}/>
          </button>
        </div>
      </div>

      {/* Logic strip */}
      <div className="px-4 pb-3">
        <div className="rounded-lg bg-ink-50/70 dark:bg-white/[0.02] border border-dashed border-ink-200 dark:border-white/10 p-3 flex flex-wrap items-center gap-2 text-[12.5px]">
          <span className="font-mono text-[11px] text-accent-700 dark:text-accent-300 font-bold">IF</span>
          <select value={r.obj} onChange={e=>upd({obj:e.target.value})}
            className="h-7 px-2 rounded-md bg-white dark:bg-ink-800 border border-ink-200 dark:border-white/10 text-[12px]">
            {OBJECTS.map(o=> <option key={o.id} value={o.id}>{o.label}</option>)}
          </select>
          <span className="text-ink-500">on</span>
          <select value={r.scope} onChange={e=>upd({scope:e.target.value})}
            className="h-7 px-2 rounded-md bg-white dark:bg-ink-800 border border-ink-200 dark:border-white/10 text-[12px]">
            {SCOPES.map(s=> <option key={s.id} value={s.id}>{s.label}</option>)}
          </select>
          <span className="text-ink-500">where</span>
          <select value={r.metric} onChange={e=>upd({metric:e.target.value})}
            className="h-7 px-2 rounded-md bg-white dark:bg-ink-800 border border-ink-200 dark:border-white/10 text-[12px]">
            {METRICS.map(m => <option key={m.id} value={m.id}>{m.label}</option>)}
          </select>
          <Seg small value={r.op} onChange={(v)=>upd({op:v})} opts={OPS_RULE}/>
          <div className="inline-flex items-center h-7 rounded-md border border-ink-200 dark:border-white/10 bg-white dark:bg-ink-800 overflow-hidden">
            <span className="px-1.5 text-[11px] text-ink-400 font-mono">{(METRICS.find(m=>m.id===r.metric)?.unit)}</span>
            <input type="number" value={r.value} onChange={e=>upd({value:+e.target.value})}
              className="w-16 h-full bg-transparent px-1 text-[12px] font-mono outline-none"/>
          </div>
          <span className="font-mono text-[11px] text-accent-700 dark:text-accent-300 font-bold ml-1">THEN</span>
          <select value={r.action} onChange={e=>upd({action:e.target.value})}
            className="h-7 px-2 rounded-md bg-white dark:bg-ink-800 border border-ink-200 dark:border-white/10 text-[12px]">
            {ACTIONS.map(a => <option key={a.id} value={a.id}>{a.label}</option>)}
          </select>
        </div>
        {r.note && <div className="mt-2 text-[12px] text-ink-500 dark:text-ink-300 px-1">{r.note}</div>}
      </div>
    </div>
  );
}

function AutomationsDrawer({ open, onClose, rules, setRules }){
  const updateRule = (id, next) => setRules(arr => arr.map(r=> r.id===id ? next : r));
  const removeRule = (id)       => setRules(arr => arr.filter(r => r.id !== id));
  const addRule = () => setRules(arr => [
    ...arr,
    { id:'r'+Date.now(), enabled:true, scope:'overview', obj:'campaign', metric:'cpa', op:'>', value:40, action:'pause', note:'New rule — describe what it does here.' }
  ]);

  const enabledCount = rules.filter(r=>r.enabled).length;

  return (
    <Drawer open={open} onClose={onClose} width={620}
      title={
        <>
          <span className="inline-flex h-7 w-7 rounded-lg bg-accent-100 text-accent-700 dark:bg-accent-500/15 dark:text-accent-200 items-center justify-center">
            <Icon name="zap" size={14}/>
          </span>
          Automations
          <Pill tone="accent" className="ml-1">{enabledCount} active</Pill>
        </>
      }
      footer={
        <>
          <Btn variant="ghost" onClick={onClose}>Done</Btn>
          <Btn variant="accent" icon="plus" onClick={addRule}>New rule</Btn>
        </>
      }>
      <div className="p-5 space-y-3">
        <div className="rounded-xl bg-accent-50 dark:bg-accent-500/5 border border-accent-200/60 dark:border-accent-500/20 p-3.5 text-[12.5px] text-accent-800 dark:text-accent-200 flex items-start gap-2.5">
          <Icon name="info" size={14} className="mt-0.5 flex-shrink-0"/>
          <div>
            <div className="font-semibold mb-0.5">How rules run</div>
            Conditions evaluate every 15 minutes against your MCP data feed. Actions log to Activity and notify your selected channels.
          </div>
        </div>
        {rules.map(r => (
          <RuleCard key={r.id} rule={r} onChange={(n)=>updateRule(r.id, n)} onDelete={()=>removeRule(r.id)}/>
        ))}
        {rules.length === 0 && (
          <div className="rounded-xl border border-dashed border-ink-200 dark:border-white/10 p-8 text-center text-ink-500 dark:text-ink-300 text-[13px]">
            No automations yet. Click <span className="font-semibold">New rule</span> to add one.
          </div>
        )}
      </div>
    </Drawer>
  );
}

Object.assign(window, { AutomationsDrawer });
