// Grape Elevate — Automations list screen

const TriggerIcon = ({ type, size = 14 }) => {
  const map = { comment: <Icons.Comment size={size} />, story: <Icons.Story size={size} />, follow: <Icons.Follow size={size} />, dm: <Icons.Send size={size} /> };
  return map[type] || <Icons.Bolt size={size} />;
};
const triggerLabel = (a) => ({ comment: 'Comentário', story: 'Story reply', follow: 'Novo seguidor', dm: 'DM recebida' }[a.trigger] || a.trigger);

function AutomationRow({ a, t, onToggle, onEdit, onDup, onDelete, onOpen }) {
  const statusPill = a.status === 'live' ? 'pill-live' : a.status === 'paused' ? 'pill-paused' : 'pill-draft';
  return (
    <div className="auto-row" onClick={onOpen}>
      <div className="auto-name">
        <div className="auto-emoji" style={{ background: a.trigger === 'comment' ? 'color-mix(in oklch, var(--coral) 18%, var(--surface))'
          : a.trigger === 'story' ? 'color-mix(in oklch, var(--grape) 18%, var(--surface))'
          : a.trigger === 'follow' ? 'color-mix(in oklch, var(--sun) 18%, var(--surface))'
          : 'color-mix(in oklch, var(--cyan) 18%, var(--surface))' }}>
          <TriggerIcon type={a.trigger} size={18} />
        </div>
        <div style={{ minWidth: 0 }}>
          <div className="auto-title">{a.name}</div>
          <div className="muted" style={{ fontSize: 12 }}>Atualizado {a.updated}</div>
        </div>
      </div>
      <div className="auto-trigger">
        <span className="pill">{triggerLabel(a)}</span>
        {a.triggerKey !== '—' && <code className="mono trigger-key">"{a.triggerKey}"</code>}
      </div>
      <div className="auto-runs">{a.runs.toLocaleString('pt-BR')}</div>
      <div className="auto-conv">
        <div className="conv-bar"><i style={{ width: `${Math.min(100, a.conv * 2)}%` }} /></div>
        <span>{a.conv.toFixed(1)}%</span>
      </div>
      <span className={`pill ${statusPill}`}>
        {a.status === 'live' && <i className="dot" style={{ width: 6, height: 6, borderRadius: '50%', background: 'currentColor' }} />}
        {t(`auto.status.${a.status === 'live' ? 'live' : a.status === 'paused' ? 'paused' : 'draft'}`)}
      </span>
      <div className="auto-actions" onClick={(e) => e.stopPropagation()}>
        <button className="switch" data-on={a.status === 'live' ? '1' : '0'} onClick={() => onToggle(a)} aria-label="toggle"><i /></button>
        <button className="btn btn-ghost btn-icon" onClick={onEdit} title="Editar"><Icons.Edit size={16} /></button>
        <button className="btn btn-ghost btn-icon" onClick={onDup} title="Duplicar"><Icons.Copy size={16} /></button>
        <button className="btn btn-ghost btn-icon" onClick={onDelete} title="Excluir"><Icons.Trash size={16} /></button>
      </div>
    </div>
  );
}

function Automations({ t, automations, setAutomations, onNav, onOpenFlow }) {
  const [filter, setFilter] = React.useState('all');
  const [q, setQ] = React.useState('');

  const filtered = automations.filter((a) => {
    if (filter === 'on' && a.status !== 'live') return false;
    if (filter === 'off' && a.status !== 'paused') return false;
    if (filter === 'drafts' && a.status !== 'draft') return false;
    if (q && !a.name.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });

  const toggle = (a) => setAutomations((xs) => xs.map((x) => x.id === a.id ? { ...x, status: x.status === 'live' ? 'paused' : 'live' } : x));
  const dup = (a) => setAutomations((xs) => [...xs, { ...a, id: 'a' + Date.now(), name: a.name + ' (cópia)', status: 'draft', runs: 0, conv: 0, updated: 'agora' }]);
  const del = (a) => setAutomations((xs) => xs.filter((x) => x.id !== a.id));

  return (
    <>
      <style>{autoStyles}</style>
      <div className="page-head">
        <div>
          <h1 className="page-title">{t('auto.title')}</h1>
          <p className="page-sub">{t('auto.subtitle')}</p>
        </div>
        <div className="row">
          <div className="search-wrap">
            <Icons.Search size={16} />
            <input className="input input-search" placeholder={t('auto.search')} value={q} onChange={(e) => setQ(e.target.value)} style={{ width: 240 }} />
          </div>
          <button className="btn btn-primary" onClick={() => onOpenFlow('new')}><Icons.Plus size={16} /> {t('auto.new')}</button>
        </div>
      </div>

      <div className="row" style={{ justifyContent: 'space-between' }}>
        <div className="seg" role="tablist">
          {[['all', t('auto.filter.all')], ['on', t('auto.filter.on')], ['off', t('auto.filter.off')], ['drafts', t('auto.filter.drafts')]].map(([k, l]) => (
            <button key={k} className={filter === k ? 'active' : ''} onClick={() => setFilter(k)}>
              {l} <span className="seg-count">{k === 'all' ? automations.length
                : k === 'on' ? automations.filter((a) => a.status === 'live').length
                : k === 'off' ? automations.filter((a) => a.status === 'paused').length
                : automations.filter((a) => a.status === 'draft').length}</span>
            </button>
          ))}
        </div>
        <div className="row soft" style={{ fontSize: 12 }}>
          <Icons.Filter size={14} /> Ordenar por: <b style={{ color: 'var(--text)' }}>Execuções ▾</b>
        </div>
      </div>

      <div className="card auto-table">
        <div className="auto-row auto-head">
          <div>{t('auto.col.name')}</div>
          <div>{t('auto.col.trigger')}</div>
          <div>{t('auto.col.runs')}</div>
          <div>{t('auto.col.conv')}</div>
          <div>{t('auto.col.status')}</div>
          <div></div>
        </div>
        {filtered.length === 0 ? (
          <div className="empty">{t('auto.empty')}</div>
        ) : filtered.map((a) => (
          <AutomationRow key={a.id} a={a} t={t}
            onToggle={toggle}
            onEdit={() => onOpenFlow(a.id)}
            onDup={() => dup(a)}
            onDelete={() => del(a)}
            onOpen={() => onOpenFlow(a.id)} />
        ))}
      </div>
    </>
  );
}

const autoStyles = `
.auto-table { padding: 0; overflow: hidden; }
.auto-row {
  display: grid;
  grid-template-columns: minmax(0, 2fr) minmax(0, 1.3fr) 100px minmax(0, 1fr) 110px 180px;
  gap: 16px;
  padding: 14px 18px;
  align-items: center;
  border-bottom: 1px solid var(--line);
  cursor: pointer;
  transition: background 120ms;
}
.auto-row:last-child { border-bottom: 0; }
.auto-row:hover { background: var(--surface-2); }
.auto-head { background: var(--surface-2); font-size: 11px; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; color: var(--text-mute); cursor: default; padding-top: 12px; padding-bottom: 12px; }
.auto-head:hover { background: var(--surface-2); }
.auto-name { display: flex; align-items: center; gap: 12px; min-width: 0; }
.auto-emoji { width: 36px; height: 36px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: var(--text); }
.auto-title { font-weight: 600; font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.auto-trigger { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; min-width: 0; }
.trigger-key { font-size: 11.5px; padding: 2px 6px; border-radius: 6px; background: var(--surface-2); color: var(--coral); }
.auto-runs { font-variant-numeric: tabular-nums; font-weight: 600; }
.auto-conv { display: flex; align-items: center; gap: 8px; font-variant-numeric: tabular-nums; font-size: 12.5px; color: var(--text-soft); }
.conv-bar { flex: 1; height: 5px; background: var(--surface-3); border-radius: 999px; overflow: hidden; min-width: 40px; }
.conv-bar i { display: block; height: 100%; background: linear-gradient(90deg, var(--cyan), var(--grape)); border-radius: 999px; }
.auto-actions { display: flex; align-items: center; gap: 4px; justify-content: flex-end; }
.seg-count { font-size: 11px; opacity: 0.65; margin-left: 4px; }
`;

window.Automations = Automations;
