/* Custom Column Builder (formula builder) =========================== */

const METRIC_TOKENS = [
  { val:'spend',          label:'Amount Spent',     kind:'$' },
  { val:'impressions',    label:'Impressions',      kind:'#' },
  { val:'clicks',         label:'Clicks',           kind:'#' },
  { val:'conversions',    label:'Conversions',      kind:'#' },
  { val:'revenue',        label:'Revenue',          kind:'$' },
  { val:'followers_ig',   label:'IG Followers',     kind:'#' },
  { val:'subscribers',    label:'Subscribers',      kind:'#' },
  { val:'video_views',    label:'Video Views',      kind:'#' },
  { val:'addtocart',      label:'Add-to-Cart',      kind:'#' },
  { val:'leads',          label:'Leads',            kind:'#' },
];

const OPS = ['+','−','×','÷','(',')'];

const FORMAT_OPTS = [
  { val:'int',        label:'1,234' },
  { val:'currency',   label:'$1,234' },
  { val:'currency2',  label:'$1,234.56' },
  { val:'pct',        label:'12.34%' },
  { val:'x',          label:'1.23×' },
];

function TokenChip({ tok, onRemove }){
  const isMetric = tok.type === 'metric';
  const isOp = tok.type === 'op';
  const isNum = tok.type === 'num';
  return (
    <div className={`inline-flex items-center gap-1.5 h-8 px-2.5 rounded-lg border text-[12.5px] font-medium
      ${isMetric ? 'bg-accent-50 text-accent-700 border-accent-200 dark:bg-accent-500/15 dark:border-accent-500/30 dark:text-accent-200' : ''}
      ${isOp ? 'bg-ink-100 text-ink-800 border-ink-200 dark:bg-white/10 dark:border-white/10 dark:text-ink-100 font-mono' : ''}
      ${isNum ? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-500/15 dark:border-emerald-500/30 dark:text-emerald-300 font-mono' : ''}
      `}>
      {isMetric && (METRIC_TOKENS.find(m=>m.val===tok.val)?.label || tok.val)}
      {isOp && <span>{tok.val}</span>}
      {isNum && <span>{tok.val}</span>}
      {onRemove && (
        <button onClick={onRemove} className="ml-0.5 -mr-1 h-5 w-5 grid place-items-center rounded hover:bg-white/40 dark:hover:bg-black/30">
          <Icon name="x" size={11}/>
        </button>
      )}
    </div>
  );
}

function CustomColumnBuilder({ open, onClose, onSave, initial }){
  const [name, setName]   = useState(initial?.name || '');
  const [formula, setFormula] = useState(initial?.formula || []);
  const [format, setFormat]   = useState(initial?.format || 'currency2');
  const [numInput, setNumInput] = useState('');

  useEffect(()=>{
    if (open) {
      setName(initial?.name || '');
      setFormula(initial?.formula || []);
      setFormat(initial?.format || 'currency2');
      setNumInput('');
    }
  }, [open, initial]);

  const add = (tok)=> setFormula(f => [...f, tok]);
  const remove = (i)=> setFormula(f => f.filter((_,idx)=>idx!==i));
  const clear = ()=> setFormula([]);

  /* Preview a stylized formula string */
  const preview = formula.length === 0 ? 'Build your formula below…' :
    formula.map(t => t.type==='metric' ? `[${(METRIC_TOKENS.find(m=>m.val===t.val)?.label||t.val)}]` : t.val).join(' ');

  /* Sample value preview (fake) */
  const sampleValue = useMemo(()=>{
    const r = formula.length ? (Math.random()*42+1) : 0;
    return formula.length ? fmt(+r.toFixed(2), format) : '—';
  }, [formula, format]);

  return (
    <Modal open={open} onClose={onClose} width={680}>
      <div className="px-6 pt-5 pb-3 flex items-center justify-between border-b border-ink-200 dark:border-white/10">
        <div className="flex items-center gap-2">
          <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="sparkles" size={14}/>
          </span>
          <div>
            <div className="text-[15px] font-semibold leading-none">Create custom column</div>
            <div className="text-[12px] text-ink-500 dark:text-ink-300 mt-1">Define a metric using existing fields and operators.</div>
          </div>
        </div>
        <button onClick={onClose} className="h-8 w-8 grid place-items-center rounded-lg hover:bg-ink-100 dark:hover:bg-white/10">
          <Icon name="x"/>
        </button>
      </div>

      <div className="px-6 py-5 space-y-5 overflow-auto">
        {/* Name + format */}
        <div className="grid grid-cols-[1fr_180px] gap-3">
          <label className="block">
            <div className="text-[11px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300 mb-1.5">Column name</div>
            <input value={name} onChange={e=>setName(e.target.value)} placeholder="e.g. Cost per IG Follower"
              className="w-full h-10 rounded-lg border border-ink-200 dark:border-white/10 bg-white dark:bg-ink-900/40 px-3 text-[13px] focus:outline-none focus:border-accent-400 focus:ring-2 focus:ring-accent-100 dark:focus:ring-accent-500/20"/>
          </label>
          <label className="block">
            <div className="text-[11px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300 mb-1.5">Format</div>
            <select value={format} onChange={e=>setFormat(e.target.value)}
              className="w-full h-10 rounded-lg border border-ink-200 dark:border-white/10 bg-white dark:bg-ink-900/40 px-3 text-[13px] focus:outline-none">
              {FORMAT_OPTS.map(f => <option key={f.val} value={f.val}>{f.label}</option>)}
            </select>
          </label>
        </div>

        {/* Formula canvas */}
        <div>
          <div className="flex items-center justify-between mb-1.5">
            <div className="text-[11px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300">Formula</div>
            <button onClick={clear} className="text-[11px] text-ink-500 hover:text-ink-800 dark:text-ink-300 dark:hover:text-white">Clear</button>
          </div>
          <div className="min-h-[64px] rounded-xl border-2 border-dashed border-ink-200 dark:border-white/10 p-3 bg-ink-50/40 dark:bg-white/[0.02] flex flex-wrap gap-2 items-center">
            {formula.length === 0 && (
              <span className="text-[12.5px] text-ink-400 dark:text-ink-400">Tap metrics and operators below to build →</span>
            )}
            {formula.map((t,i)=>(<TokenChip key={i} tok={t} onRemove={()=>remove(i)}/>))}
          </div>

          {/* Preview line */}
          <div className="mt-3 rounded-lg bg-ink-900/95 dark:bg-black text-white font-mono text-[12.5px] px-3 py-2 flex items-center justify-between">
            <span className="opacity-80 truncate">{preview}</span>
            <span className="ml-3 px-2 py-0.5 rounded bg-accent-500/20 text-accent-200">{sampleValue}</span>
          </div>
        </div>

        {/* Token palette */}
        <div className="grid grid-cols-[1fr_220px] gap-4">
          <div>
            <div className="text-[11px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300 mb-1.5">Metrics</div>
            <div className="flex flex-wrap gap-1.5">
              {METRIC_TOKENS.map(m => (
                <button key={m.val} onClick={()=>add({type:'metric', val:m.val})}
                  className="inline-flex items-center gap-1.5 h-8 px-2.5 rounded-lg border border-ink-200 hover:border-accent-300 hover:bg-accent-50 dark:border-white/10 dark:hover:bg-accent-500/10 dark:hover:border-accent-500/40 text-[12.5px] transition">
                  <span className="text-[10px] font-mono opacity-50">{m.kind}</span>
                  {m.label}
                </button>
              ))}
            </div>
          </div>
          <div>
            <div className="text-[11px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300 mb-1.5">Operators</div>
            <div className="flex flex-wrap gap-1.5">
              {OPS.map(op => (
                <button key={op} onClick={()=>add({type:'op', val:op})}
                  className="h-8 w-8 rounded-lg border border-ink-200 hover:bg-ink-100 dark:border-white/10 dark:hover:bg-white/10 text-[14px] font-mono">{op}</button>
              ))}
            </div>
            <div className="mt-3 text-[11px] uppercase tracking-wide font-semibold text-ink-500 dark:text-ink-300 mb-1.5">Constant</div>
            <div className="flex gap-1.5">
              <input type="number" value={numInput} onChange={e=>setNumInput(e.target.value)}
                placeholder="123"
                className="w-full h-8 rounded-lg border border-ink-200 dark:border-white/10 bg-white dark:bg-ink-900/40 px-2 text-[12.5px] font-mono"/>
              <button onClick={()=>{ if(numInput!==''){ add({type:'num', val:numInput}); setNumInput(''); } }}
                className="h-8 px-3 rounded-lg bg-ink-900 dark:bg-white text-white dark:text-ink-900 text-[12px] font-medium">Add</button>
            </div>
          </div>
        </div>
      </div>

      <div className="px-6 h-14 border-t border-ink-200 dark:border-white/10 flex items-center justify-between bg-ink-50/40 dark:bg-white/[0.02]">
        <div className="text-[12px] text-ink-500 dark:text-ink-300">
          Saved columns are pinned to your view.
        </div>
        <div className="flex items-center gap-2">
          <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
          <Btn variant="accent" icon="check"
            onClick={()=>{ if(!name.trim() || formula.length===0) return; onSave({ id:'cc_'+Date.now(), name, formula, format }); onClose(); }}>
            Save column
          </Btn>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { CustomColumnBuilder });
