// 1Radar — Workflow home: gallery of saved workflows (Canva-style)

function fmtDate(iso) {
  const d = new Date(iso);
  return d.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' });
}

// Compute a thumbnail preview from actual node/edge data
function buildPreview(nodes, edges) {
  if (!nodes || nodes.length === 0) return { nodes: [], edges: [] };

  // Compute bounding box of all nodes
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  for (const n of nodes) {
    minX = Math.min(minX, n.x);
    minY = Math.min(minY, n.y);
    maxX = Math.max(maxX, n.x + (n.w || 240));
    maxY = Math.max(maxY, n.y + 80);
  }
  const W = 284, H = 132, PAD = 16;
  const scaleX = (W - PAD * 2) / Math.max(maxX - minX, 1);
  const scaleY = (H - PAD * 2) / Math.max(maxY - minY, 1);
  const scale  = Math.min(scaleX, scaleY);

  const tx = (v) => PAD + (v - minX) * scale;
  const ty = (v) => PAD + (v - minY) * scale;

  // Node type → color mapping (matches NODE_DEFAULTS colours)
  const typeColor = {
    'prompt': '#335CFF', 'image-in': '#335CFF', 'video-in': '#335CFF',
    'ad-in': '#335CFF', 'brand-in': '#335CFF',
    'img-gen': '#7B5BFF', 'vid-gen': '#7B5BFF', 'copy-gen': '#7B5BFF', 'transcribe': '#7B5BFF',
    'bg-remove': '#10B981',
    'save': '#F59E0B', 'export': '#F59E0B',
    'trigger-schedule': '#F97316', 'trigger-ad-saved': '#F97316',
  };

  const previewNodes = nodes.map(n => ({
    x: tx(n.x), y: ty(n.y),
    w: Math.max(24, (n.w || 240) * scale),
    h: Math.max(14, 28 * scale),
    color: typeColor[n.type] || '#94A3B8',
  }));

  const nodeMap = {};
  for (const n of nodes) nodeMap[n.id] = n;

  const previewEdges = (edges || []).map(e => {
    const from = nodeMap[e.from];
    const to   = nodeMap[e.to];
    if (!from || !to) return null;
    return {
      x1: tx(from.x + (from.w || 240)),
      y1: ty(from.y + 40),
      x2: tx(to.x),
      y2: ty(to.y + 40),
    };
  }).filter(Boolean);

  return { nodes: previewNodes, edges: previewEdges };
}

// Mini SVG preview of a node graph
function WorkflowPreviewSVG({ nodes, edges }) {
  return (
    <svg viewBox="0 0 284 132" style={{ width: '100%', height: '100%', display: 'block' }}>
      <defs>
        <pattern id="dots" x="0" y="0" width="16" height="16" patternUnits="userSpaceOnUse">
          <circle cx="1" cy="1" r="1" fill="rgba(255,255,255,0.08)"/>
        </pattern>
      </defs>
      <rect width="284" height="132" fill="#0E121B"/>
      <rect width="284" height="132" fill="url(#dots)"/>

      {(edges || []).map((e, i) => {
        const mx = (e.x1 + e.x2) / 2;
        return (
          <path key={i}
            d={`M${e.x1},${e.y1} C${mx},${e.y1} ${mx},${e.y2} ${e.x2},${e.y2}`}
            fill="none" stroke="rgba(255,255,255,0.22)" strokeWidth="1.5"/>
        );
      })}

      {(nodes || []).map((n, i) => (
        <g key={i}>
          <rect x={n.x} y={n.y} width={n.w} height={n.h} rx="6"
            fill={n.color} fillOpacity="0.18" stroke={n.color} strokeWidth="1.5"/>
          <rect x={n.x} y={n.y} width={n.w} height={Math.max(4, n.h * 0.25)}
            rx="6" fill={n.color} fillOpacity="0.7"/>
          <circle cx={n.x}       cy={n.y + n.h / 2} r="3" fill={n.color} fillOpacity="0.8"/>
          <circle cx={n.x + n.w} cy={n.y + n.h / 2} r="3" fill={n.color} fillOpacity="0.8"/>
        </g>
      ))}
    </svg>
  );
}

function WorkflowCard({ wf, onOpen, onDelete }) {
  const [hover, setHover] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const preview = React.useMemo(() => {
    // If preview is already computed (from DB summary), use it.
    // Otherwise compute on the fly (when nodes are present).
    if (wf.preview && wf.preview.nodes && wf.preview.nodes.length > 0) return wf.preview;
    if (wf.nodes && wf.nodes.length > 0) return buildPreview(wf.nodes, wf.edges);
    return { nodes: [], edges: [] };
  }, [wf]);

  const nodeCount = wf.nodes ? wf.nodes.length : (wf.nodeCount || 0);

  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setMenuOpen(false); }}
      style={{
        display: 'flex', flexDirection: 'column',
        borderRadius: 12,
        border: `1px solid ${hover ? 'var(--accent)' : 'var(--border)'}`,
        background: 'var(--bg-surface)',
        overflow: 'hidden',
        transition: 'border-color 150ms, box-shadow 150ms, transform 150ms',
        transform: hover ? 'translateY(-2px)' : 'translateY(0)',
        boxShadow: hover
          ? '0 8px 24px rgba(14,18,27,0.14), 0 2px 6px rgba(14,18,27,0.06)'
          : '0 1px 3px rgba(14,18,27,0.06)',
        position: 'relative',
      }}
    >
      {/* Preview area */}
      <div
        onClick={() => onOpen(wf._id || wf.id)}
        style={{ height: 130, overflow: 'hidden', position: 'relative', background: '#0E121B', cursor: 'pointer' }}
      >
        <WorkflowPreviewSVG nodes={preview.nodes} edges={preview.edges}/>
        {hover && (
          <div style={{
            position: 'absolute', inset: 0, background: 'rgba(51,92,255,0.10)',
            display: 'grid', placeItems: 'center',
          }}>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              background: 'var(--accent)', color: '#fff',
              borderRadius: 8, padding: '6px 14px',
              fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-display)',
            }}>
              <Icon name="edit" size={14}/>
              Ouvrir
            </div>
          </div>
        )}
      </div>

      {/* Footer */}
      <div style={{ padding: '10px 14px 12px', display: 'flex', alignItems: 'flex-start', gap: 8 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 13, fontFamily: 'var(--font-display)', marginBottom: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {wf.name || 'Untitled workflow'}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>
              {fmtDate(wf.updatedAt)}
            </span>
            <span style={{ fontSize: 11, color: 'var(--text-faint)', display: 'inline-flex', alignItems: 'center', gap: 3 }}>
              <Icon name="workflow" size={11}/>
              {nodeCount} nodes
            </span>
          </div>
        </div>

        {/* Context menu button */}
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <button
            onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v); }}
            className="btn btn-ghost btn-icon"
            style={{ width: 26, height: 26, opacity: hover || menuOpen ? 1 : 0, transition: 'opacity 150ms' }}
          >
            <Icon name="more" size={14}/>
          </button>
          {menuOpen && (
            <>
              <div onClick={() => setMenuOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 10 }}/>
              <div style={{
                position: 'absolute', right: 0, bottom: '100%', marginBottom: 4,
                zIndex: 11, minWidth: 140,
                background: 'var(--bg-surface)', border: '1px solid var(--border)',
                borderRadius: 10, boxShadow: '0 8px 24px rgba(14,18,27,0.18)',
                padding: 4,
              }}>
                <button
                  onClick={(e) => { e.stopPropagation(); setMenuOpen(false); onOpen(wf._id || wf.id); }}
                  className="btn btn-ghost"
                  style={{ width: '100%', justifyContent: 'flex-start', gap: 8, fontSize: 13, padding: '7px 10px', borderRadius: 6 }}
                >
                  <Icon name="edit" size={13} style={{ color: 'var(--text-faint)' }}/>
                  Ouvrir
                </button>
                <div style={{ height: 1, background: 'var(--border-soft)', margin: '4px 6px' }}/>
                <button
                  onClick={(e) => { e.stopPropagation(); setMenuOpen(false); onDelete(wf._id || wf.id); }}
                  className="btn btn-ghost"
                  style={{ width: '100%', justifyContent: 'flex-start', gap: 8, fontSize: 13, padding: '7px 10px', borderRadius: 6, color: 'var(--danger)' }}
                >
                  <Icon name="trash" size={13} style={{ color: 'var(--danger)' }}/>
                  Supprimer
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function NewWorkflowCard({ onCreate }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onClick={onCreate}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        borderRadius: 12,
        border: `1.5px dashed ${hover ? 'var(--accent)' : 'var(--border)'}`,
        background: hover ? 'var(--bg-soft)' : 'transparent',
        cursor: 'pointer',
        minHeight: 192,
        gap: 10,
        transition: 'border-color 150ms, background 150ms',
      }}
    >
      <div style={{
        width: 44, height: 44, borderRadius: 12,
        background: hover ? 'var(--accent)' : 'var(--bg-soft)',
        border: hover ? 'none' : '1.5px dashed var(--border)',
        color: hover ? '#fff' : 'var(--text-faint)',
        display: 'grid', placeItems: 'center',
        transition: 'background 150ms, color 150ms, border-color 150ms',
      }}>
        <Icon name="plus" size={22}/>
      </div>
      <span style={{
        fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-display)',
        color: hover ? 'var(--accent)' : 'var(--text-muted)',
        transition: 'color 150ms',
      }}>
        Nouveau workflow
      </span>
    </div>
  );
}

const WorkflowHomeV3 = ({ onOpen, onNew }) => {
  const [workflows, setWorkflows] = React.useState([]);
  const [loading, setLoading]     = React.useState(true);
  const [search, setSearch]       = React.useState('');

  const load = () => {
    setLoading(true);
    apiFetch('/workflows')
      .then(setWorkflows)
      .catch(() => setWorkflows([]))
      .finally(() => setLoading(false));
  };

  React.useEffect(() => { load(); }, []);

  const handleDelete = async (id) => {
    if (!confirm('Supprimer ce workflow ?')) return;
    try {
      await apiFetch(`/workflows/${id}`, 'DELETE');
      setWorkflows(prev => prev.filter(w => (w._id || w.id) !== id));
    } catch {}
  };

  const filtered = search.trim()
    ? workflows.filter(w => w.name.toLowerCase().includes(search.toLowerCase()))
    : workflows;

  return (
    <>
      <PageHeader
        icon="workflow"
        title="Workflows"
        subtitle="Automatisez vos pipelines créatifs"
        right={
          <button className="btn btn-primary btn-sm" onClick={onNew}>
            <Icon name="plus" size={14}/>
            Nouveau workflow
          </button>
        }
      />

      <div style={{ flex: 1, overflowY: 'auto', padding: '24px 28px' }} className="scroll">

        {/* Search bar */}
        <div style={{ maxWidth: 320, marginBottom: 28 }}>
          <div style={{ position: 'relative' }}>
            <Icon name="search" size={14} style={{
              position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)',
              color: 'var(--text-faint)', pointerEvents: 'none',
            }}/>
            <input
              className="fld"
              type="text"
              placeholder="Rechercher un workflow…"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              style={{ paddingLeft: 32, fontSize: 13 }}
            />
          </div>
        </div>

        {loading ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--text-faint)', fontSize: 13 }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--accent)', display: 'inline-block', animation: 'pulse 1s infinite' }}/>
            Chargement…
          </div>
        ) : (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
            gap: 16,
          }}>
            {!search.trim() && <NewWorkflowCard onCreate={onNew}/>}

            {filtered.map(wf => (
              <WorkflowCard key={wf._id || wf.id} wf={wf} onOpen={onOpen} onDelete={handleDelete}/>
            ))}

            {search.trim() && filtered.length === 0 && (
              <div style={{
                gridColumn: '1 / -1', padding: '48px 0',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
                color: 'var(--text-faint)',
              }}>
                <Icon name="search" size={32}/>
                <span style={{ fontSize: 14 }}>Aucun workflow trouvé pour « {search} »</span>
              </div>
            )}

            {!search.trim() && filtered.length === 0 && !loading && (
              <div style={{
                gridColumn: '1 / -1', padding: '48px 0',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
                color: 'var(--text-faint)',
              }}>
                <Icon name="workflow" size={32}/>
                <span style={{ fontSize: 14 }}>Aucun workflow pour l'instant</span>
                <button className="btn btn-stroke btn-sm" onClick={onNew}>
                  <Icon name="plus" size={14}/> Créer un workflow
                </button>
              </div>
            )}
          </div>
        )}
      </div>
    </>
  );
};

Object.assign(window, { WorkflowHomeV3 });
