// Admin → Automations — workflow rule builder & run log
function AutoToggle({ on, onChange, disabled }) {
  return (
    <button onClick={() => !disabled && onChange(!on)} disabled={disabled}
      style={{ width: 38, height: 22, borderRadius: 999, border: 'none', cursor: disabled ? 'not-allowed' : 'pointer', flexShrink: 0,
        background: on ? 'var(--won)' : 'var(--border-strong)', position: 'relative', transition: 'background 0.15s', opacity: disabled ? 0.5 : 1 }}>
      <span style={{ position: 'absolute', top: 2, left: on ? 18 : 2, width: 18, height: 18, borderRadius: '50%', background: 'white', transition: 'left 0.15s', boxShadow: '0 1px 2px rgba(0,0,0,0.2)' }}></span>
    </button>
  );
}
function Automations({ automations, log, reps, showrooms, currentUser, onSave, onDelete, onToggle }) {
  const canEdit = ['admin', 'leadership'].includes(currentUser.role) || currentUser.superAdmin;
  const [editing, setEditing] = React.useState(null);
  const [adding, setAdding] = React.useState(false);
  const T = window.AUTOMATION_TRIGGERS || [];
  const A = window.AUTOMATION_ACTIONS || [];

  const totalRuns = (automations || []).reduce((s, r) => s + (r.runCount || 0), 0);
  const activeCount = (automations || []).filter(r => r.enabled).length;

  return (
    <div>
      <div className="card" style={{ marginBottom: 16, padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 14, background: 'var(--accent-soft)', border: '1px solid color-mix(in oklch, var(--accent) 22%, transparent)' }}>
        <div style={{ width: 32, height: 32, borderRadius: 16, background: 'var(--accent)', color: 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
          <Icon name="spark" size={16} color="white"/>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--accent-ink)', marginBottom: 2 }}>Workflow automations</div>
          <div style={{ fontSize: 12, color: 'var(--accent-ink)' }}>
            Put the busywork on autopilot — when something happens in the pipeline, Pearler runs your rules automatically. {activeCount} active · {totalRuns} total runs.
          </div>
        </div>
        {canEdit && <button className="btn primary" onClick={() => { setEditing(null); setAdding(true); }}><Icon name="plus" size={12}/> New automation</button>}
      </div>

      <div className="grid-2">
        <div className="card">
          <div className="card-hd">
            <div><div className="card-title">Rules ({(automations || []).length})</div><div className="card-sub">Run in order, top to bottom</div></div>
          </div>
          <div style={{ padding: '6px 0' }}>
            {(automations || []).length === 0 && <div className="empty">No automations yet. Create one to get started.</div>}
            {(automations || []).map(rule => {
              const sum = window.automationSummary(rule);
              return (
                <div key={rule.id} style={{ padding: '12px 18px', borderBottom: '1px solid var(--border)', display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                  <AutoToggle on={rule.enabled} onChange={(v) => onToggle(rule.id, v)} disabled={!canEdit}/>
                  <div style={{ flex: 1, minWidth: 0, opacity: rule.enabled ? 1 : 0.55 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{rule.name}</div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginTop: 5, fontSize: 11 }}>
                      <span className="pill" style={{ background: 'var(--info-soft)', color: 'oklch(0.4 0.09 240)' }}><Icon name="alert" size={10}/> {sum.trigger}</span>
                      {(rule.conditions || []).length > 0 && <span className="pill" style={{ fontSize: 10 }}>{rule.conditions.length} condition{rule.conditions.length > 1 ? 's' : ''}</span>}
                      <Icon name="arrow-right" size={11} color="var(--ink-4)"/>
                      {sum.actions.map((a, i) => <span key={i} className="pill" style={{ background: 'var(--accent-soft)', color: 'var(--accent-ink)', fontSize: 10 }}>{a}</span>)}
                    </div>
                    <div style={{ fontSize: 10.5, color: 'var(--ink-4)', marginTop: 5 }}>
                      Ran <span className="num">{rule.runCount || 0}</span>×{rule.lastRun ? ' · last ' + rule.lastRun : ' · never'}
                    </div>
                  </div>
                  {canEdit && (
                    <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
                      <button className="btn icon sm" onClick={() => { setAdding(false); setEditing(rule); }}><Icon name="edit" size={12}/></button>
                      <button className="btn icon sm" style={{ color: 'var(--lost)' }} onClick={() => { if (confirm('Delete automation "' + rule.name + '"?')) onDelete(rule.id); }}><Icon name="close" size={12}/></button>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        <div className="card">
          <div className="card-hd">
            <div><div className="card-title">Recent activity</div><div className="card-sub">Last automations that fired</div></div>
          </div>
          {(!log || log.length === 0) ? (
            <div className="empty">Nothing yet. Create or edit a deal/contact to see rules fire.</div>
          ) : (
            <div className="activity-list" style={{ padding: '10px 18px' }}>
              {log.slice(0, 25).map((l, i) => (
                <div className="activity-item" key={i} style={{ alignItems: 'flex-start' }}>
                  <span className="activity-dot" style={{ background: 'var(--accent)' }}></span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 500 }}>{l.ruleName}</div>
                    <div className="activity-meta">{l.subject ? l.subject + ' · ' : ''}{l.ts}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {(editing || adding) && (
        <RuleEditor
          rule={editing}
          reps={reps}
          showrooms={showrooms}
          onClose={() => { setEditing(null); setAdding(false); }}
          onSave={(r) => { onSave(r); setEditing(null); setAdding(false); }}
        />
      )}
    </div>
  );
}

function RuleEditor({ rule, reps, showrooms, onClose, onSave }) {
  const TRIGGERS = window.AUTOMATION_TRIGGERS || [];
  const CONDS = window.AUTOMATION_CONDITIONS || [];
  const ACTIONS = window.AUTOMATION_ACTIONS || [];
  const stages = (window.SALES_DATA && window.SALES_DATA.STAGES) || [];
  const apptTypes = window.apptTypes ? window.apptTypes() : [{ id: 'followup_call', label: 'Follow-up call' }];

  const [d, setD] = React.useState(rule || { name: '', enabled: true, trigger: { type: 'deal_created' }, conditions: [], actions: [{ type: 'create_task', days: 2, taskType: 'followup_call' }] });
  const set = (patch) => setD(p => ({ ...p, ...patch }));
  const valid = d.name.trim() && d.trigger.type && (d.actions || []).length > 0;

  const addCond = () => set({ conditions: [...(d.conditions || []), { field: 'showroom', value: showrooms[0]?.id || '' }] });
  const setCond = (i, patch) => set({ conditions: d.conditions.map((c, j) => j === i ? { ...c, ...patch } : c) });
  const delCond = (i) => set({ conditions: d.conditions.filter((_, j) => j !== i) });

  const addAction = () => set({ actions: [...(d.actions || []), { type: 'notify', text: '' }] });
  const setAction = (i, patch) => set({ actions: d.actions.map((a, j) => j === i ? { ...a, ...patch } : a) });
  const delAction = (i) => set({ actions: d.actions.filter((_, j) => j !== i) });

  const condInput = (c, i) => {
    const def = CONDS.find(x => x.id === c.field) || {};
    if (def.type === 'showroom') return <select className="sel" value={c.value} onChange={(e) => setCond(i, { value: e.target.value })}>{showrooms.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}</select>;
    if (def.type === 'rep') return <select className="sel" value={c.value} onChange={(e) => setCond(i, { value: e.target.value })}>{reps.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}</select>;
    if (def.type === 'number') return <input type="number" value={c.value} onChange={(e) => setCond(i, { value: e.target.value })} placeholder="20000" style={{ width: 110 }}/>;
    return <input value={c.value} onChange={(e) => setCond(i, { value: e.target.value })} placeholder="Kitchen" style={{ width: 140 }}/>;
  };

  const actionParams = (a, i) => {
    if (a.type === 'create_task') return (
      <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
        <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>in</span>
        <input type="number" value={a.days != null ? a.days : 2} onChange={(e) => setAction(i, { days: Number(e.target.value) })} style={{ width: 56 }}/>
        <span style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>days ·</span>
        <select className="sel" value={a.taskType || 'followup_call'} onChange={(e) => setAction(i, { taskType: e.target.value })}>{apptTypes.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}</select>
      </div>
    );
    if (a.type === 'log_note' || a.type === 'notify') return <input value={a.text || ''} onChange={(e) => setAction(i, { text: e.target.value })} placeholder={a.type === 'notify' ? 'Notification message…' : 'Note text…'} style={{ flex: 1, minWidth: 180 }}/>;
    if (a.type === 'reassign') return <select className="sel" value={a.rep || ''} onChange={(e) => setAction(i, { rep: e.target.value })}><option value="">Choose designer…</option>{reps.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}</select>;
    return null;
  };

  return (
    <div>
      <div className="detail-overlay" onClick={onClose} style={{ zIndex: 56 }}/>
      <div className="invite-modal" style={{ zIndex: 57, width: 600 }}>
        <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ fontSize: 17, fontWeight: 600 }}>{rule ? 'Edit automation' : 'New automation'}</div>
          <button className="detail-close" style={{ marginLeft: 'auto' }} onClick={onClose}><Icon name="close" size={16}/></button>
        </div>

        <div style={{ padding: '18px 22px', maxHeight: '68vh', overflowY: 'auto' }}>
          <div className="detail-field" style={{ marginBottom: 18 }}>
            <span className="lbl">Automation name</span>
            <input value={d.name} onChange={(e) => set({ name: e.target.value })} placeholder="e.g. New lead → follow-up in 2 days" autoFocus/>
          </div>

          {/* Trigger */}
          <div style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--ink-3)', fontWeight: 600, marginBottom: 7 }}>When this happens</div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
            <select className="sel" value={d.trigger.type} onChange={(e) => set({ trigger: { type: e.target.value } })} style={{ flex: 1, minWidth: 220 }}>
              {TRIGGERS.map(t => <option key={t.id} value={t.id}>{t.label}</option>)}
            </select>
            {d.trigger.type === 'deal_stage' && (
              <select className="sel" value={d.trigger.stage || (stages[0] && stages[0].id)} onChange={(e) => set({ trigger: { type: 'deal_stage', stage: e.target.value } })}>
                {stages.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
              </select>
            )}
          </div>

          {/* Conditions */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 7 }}>
            <div style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--ink-3)', fontWeight: 600 }}>Only if (optional)</div>
            <button className="btn sm" onClick={addCond}><Icon name="plus" size={11}/> Add condition</button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 18 }}>
            {(d.conditions || []).length === 0 && <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>Runs for every matching event.</div>}
            {(d.conditions || []).map((c, i) => (
              <div key={i} style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
                <select className="sel" value={c.field} onChange={(e) => setCond(i, { field: e.target.value, value: '' })}>{CONDS.map(x => <option key={x.id} value={x.id}>{x.label}</option>)}</select>
                {condInput(c, i)}
                <button className="btn icon sm" style={{ marginLeft: 'auto' }} onClick={() => delCond(i)}><Icon name="close" size={12}/></button>
              </div>
            ))}
          </div>

          {/* Actions */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 7 }}>
            <div style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--ink-3)', fontWeight: 600 }}>Do this</div>
            <button className="btn sm" onClick={addAction}><Icon name="plus" size={11}/> Add action</button>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {(d.actions || []).map((a, i) => (
              <div key={i} style={{ display: 'flex', gap: 6, alignItems: 'center', padding: '8px 10px', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', background: 'var(--surface-2)', flexWrap: 'wrap' }}>
                <select className="sel" value={a.type} onChange={(e) => setAction(i, { type: e.target.value })}>{ACTIONS.map(x => <option key={x.id} value={x.id}>{x.label}</option>)}</select>
                {actionParams(a, i)}
                <button className="btn icon sm" style={{ marginLeft: 'auto' }} onClick={() => delAction(i)}><Icon name="close" size={12}/></button>
              </div>
            ))}
          </div>
        </div>

        <div style={{ padding: '13px 22px', borderTop: '1px solid var(--border)', background: 'var(--surface-2)', display: 'flex', gap: 8 }}>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!valid} style={{ marginLeft: 'auto', opacity: valid ? 1 : 0.5 }} onClick={() => onSave(d)}><Icon name="check" size={12}/> Save automation</button>
        </div>
      </div>
    </div>
  );
}

window.Automations = Automations;
