// Workflow Builder — drag nodes on a canvas
const WorkflowsPage = () => {
  const [tab, setTab] = useState('builder');
  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Workflows</h1>
          <div className="page-sub">24 active workflows · 3 drafts · 1,284 runs in last 24h</div>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="copy" size={12}/>Templates</button>
          <button className="btn"><Icon name="play" size={12}/>Test run</button>
          <button className="btn primary"><Icon name="check" size={12}/>Publish workflow</button>
        </div>
      </div>

      <div className="tabs">
        <div className={`tab ${tab==='builder'?'active':''}`} onClick={()=>setTab('builder')}>Builder</div>
        <div className={`tab ${tab==='runs'?'active':''}`} onClick={()=>setTab('runs')}>Run history<span className="count">1,284</span></div>
        <div className={`tab ${tab==='all'?'active':''}`} onClick={()=>setTab('all')}>All workflows<span className="count">27</span></div>
        <div className={`tab ${tab==='triggers'?'active':''}`} onClick={()=>setTab('triggers')}>Triggers</div>
      </div>

      {tab === 'builder' && <WorkflowBuilder/>}
      {tab === 'runs' && <RunHistory/>}
      {tab === 'all' && <AllWorkflows/>}
      {tab === 'triggers' && <TriggersList/>}
    </>
  );
};

const NODE_LIBRARY = [
  { type: 'trigger', label: 'Machine event', icon: 'cpu', desc: 'When a sensor crosses a threshold' },
  { type: 'trigger', label: 'Schedule', icon: 'clock', desc: 'Run on a recurring schedule' },
  { type: 'trigger', label: 'Form submitted', icon: 'form', desc: 'When an operator submits a form' },
  { type: 'trigger', label: 'Webhook', icon: 'link', desc: 'External system event' },
  { type: 'condition', label: 'If/Else', icon: 'branch', desc: 'Branch on a condition' },
  { type: 'condition', label: 'Threshold', icon: 'alertCircle', desc: 'Numeric threshold check' },
  { type: 'condition', label: 'Wait', icon: 'clock', desc: 'Delay execution' },
  { type: 'action', label: 'Notify', icon: 'bell', desc: 'Send notification' },
  { type: 'action', label: 'Create ticket', icon: 'wrench', desc: 'Create maintenance ticket' },
  { type: 'action', label: 'Update record', icon: 'database', desc: 'Write to a record' },
  { type: 'action', label: 'Escalate', icon: 'zap', desc: 'Escalate to next role' },
];

const initialNodes = [
  { id: 'n1', type: 'trigger', subtype: 'Machine event', x: 60,  y: 80,  title: 'When CNC-04 spindle temp', detail: '> 85°C for 30s' },
  { id: 'n2', type: 'condition', subtype: 'If/Else', x: 320, y: 80, title: 'If shift is active', detail: 'shift ∈ {A, B, C}' },
  { id: 'n3', type: 'action', subtype: 'Notify', x: 580, y: 30, title: 'Notify maintenance lead', detail: 'SMS · Slack #maint-pune' },
  { id: 'n4', type: 'action', subtype: 'Create ticket', x: 580, y: 140, title: 'Create maintenance ticket', detail: 'priority: high · auto-assign' },
  { id: 'n5', type: 'condition', subtype: 'Wait', x: 840, y: 80, title: 'Wait 5 minutes', detail: 'check acknowledgment' },
  { id: 'n6', type: 'action', subtype: 'Escalate', x: 1100, y: 80, title: 'Escalate to plant supervisor', detail: 'if not acknowledged' },
];
const initialEdges = [
  { from: 'n1', to: 'n2' },
  { from: 'n2', to: 'n3', label: 'yes' },
  { from: 'n2', to: 'n4', label: 'yes' },
  { from: 'n3', to: 'n5' },
  { from: 'n4', to: 'n5' },
  { from: 'n5', to: 'n6' },
];

const WorkflowBuilder = () => {
  const [nodes, setNodes] = useState(initialNodes);
  const [edges] = useState(initialEdges);
  const [selected, setSelected] = useState('n1');
  const [drag, setDrag] = useState(null);
  const canvasRef = useRef(null);
  const toast = useToast();

  const onMouseDown = (e, node) => {
    const rect = canvasRef.current.getBoundingClientRect();
    setDrag({ id: node.id, dx: e.clientX - rect.left - node.x, dy: e.clientY - rect.top - node.y });
    setSelected(node.id);
  };
  useEffect(() => {
    if (!drag) return;
    const move = (e) => {
      const rect = canvasRef.current.getBoundingClientRect();
      setNodes(ns => ns.map(n => n.id === drag.id ? { ...n, x: Math.max(0, e.clientX - rect.left - drag.dx), y: Math.max(0, e.clientY - rect.top - drag.dy) } : n));
    };
    const up = () => setDrag(null);
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseup', up);
    return () => { window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); };
  }, [drag]);

  const sel = nodes.find(n => n.id === selected);

  const handleDropNew = (item) => {
    const id = 'n' + (nodes.length + 10);
    setNodes(ns => [...ns, { id, type: item.type, subtype: item.label, x: 200 + Math.random()*200, y: 250 + Math.random()*40, title: item.label, detail: item.desc }]);
    toast.push(`Added "${item.label}" node`);
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr 320px', height: 'calc(100vh - 44px - 91px - 40px)' }}>
      {/* Left palette */}
      <div style={{ borderRight: '1px solid var(--line)', background: 'var(--panel)', overflowY: 'auto', padding: '14px 12px' }}>
        <div style={{ fontSize: 12, fontWeight: 500, marginBottom: 8 }}>High-temp escalation</div>
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--text-3)', marginBottom: 14 }}>v3 · 12 runs today · last 14:31</div>

        <div className="sec-heading">Triggers</div>
        {NODE_LIBRARY.filter(n => n.type === 'trigger').map(n => <PaletteItem key={n.label} item={n} onDrop={handleDropNew}/>)}

        <div className="sec-heading">Conditions</div>
        {NODE_LIBRARY.filter(n => n.type === 'condition').map(n => <PaletteItem key={n.label} item={n} onDrop={handleDropNew}/>)}

        <div className="sec-heading">Actions</div>
        {NODE_LIBRARY.filter(n => n.type === 'action').map(n => <PaletteItem key={n.label} item={n} onDrop={handleDropNew}/>)}
      </div>

      {/* Canvas */}
      <div ref={canvasRef} className="dotgrid" style={{ position: 'relative', overflow: 'auto', background: 'var(--bg)' }}>
        <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', pointerEvents: 'none' }}>
          <defs>
            <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto">
              <path d="M0,0 L10,5 L0,10 z" fill="var(--text-3)"/>
            </marker>
          </defs>
          {edges.map((e, i) => {
            const a = nodes.find(n => n.id === e.from);
            const b = nodes.find(n => n.id === e.to);
            if (!a || !b) return null;
            const x1 = a.x + 200, y1 = a.y + 28;
            const x2 = b.x, y2 = b.y + 28;
            const cx = (x1 + x2) / 2;
            return (
              <g key={i}>
                <path d={`M${x1},${y1} C${cx},${y1} ${cx},${y2} ${x2},${y2}`}
                  fill="none" stroke="var(--text-3)" strokeWidth="1.5" markerEnd="url(#arrow)"/>
                {e.label && (
                  <g transform={`translate(${cx} ${(y1+y2)/2 - 8})`}>
                    <rect x="-12" y="-7" width="24" height="14" rx="2" fill="var(--panel)" stroke="var(--line)"/>
                    <text textAnchor="middle" y="3" fontSize="10" fill="var(--text-2)" fontFamily="JetBrains Mono">{e.label}</text>
                  </g>
                )}
              </g>
            );
          })}
        </svg>

        {nodes.map(n => (
          <div key={n.id} className={`wf-node ${n.type} ${selected === n.id ? 'selected' : ''}`}
            style={{ left: n.x, top: n.y }}
            onMouseDown={e => onMouseDown(e, n)}>
            <div className="wf-port in"/>
            <div className="wf-port out"/>
            <div className="wf-node-head">
              <Icon name={n.type === 'trigger' ? 'zap' : n.type === 'condition' ? 'branch' : 'arrowRight'} size={11}/>
              <span>{n.type} · {n.subtype}</span>
            </div>
            <div className="wf-node-title">{n.title}</div>
            <div className="mono" style={{ fontSize: 10.5, color: 'var(--text-3)', marginTop: 4 }}>{n.detail}</div>
          </div>
        ))}

        {/* Mini map / status */}
        <div style={{ position: 'absolute', bottom: 12, right: 12, display: 'flex', gap: 6 }}>
          <button className="btn sm icon"><Icon name="plus" size={12}/></button>
          <button className="btn sm icon">−</button>
          <button className="btn sm">100%</button>
          <button className="btn sm"><Icon name="expand" size={11}/>Fit</button>
        </div>

        <div style={{ position: 'absolute', top: 12, left: 12, display: 'flex', gap: 6 }}>
          <span className="pill running"><span className="dot"/>Published</span>
          <span className="pill" style={{ background: 'var(--panel)', border: '1px solid var(--line)' }}>{nodes.length} nodes</span>
          <span className="pill" style={{ background: 'var(--panel)', border: '1px solid var(--line)' }}>{edges.length} edges</span>
        </div>
      </div>

      {/* Right config panel */}
      <div style={{ borderLeft: '1px solid var(--line)', background: 'var(--panel)', overflowY: 'auto' }}>
        {sel ? <NodeConfig node={sel}/> : <div style={{ padding: 20, color: 'var(--text-3)', fontSize: 12 }}>Select a node to configure</div>}
      </div>
    </div>
  );
};

const PaletteItem = ({ item, onDrop }) => {
  const colorMap = { trigger: 'var(--accent)', condition: 'var(--blue)', action: 'var(--green)' };
  return (
    <div onClick={() => onDrop(item)}
      style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '8px 10px', borderRadius: 4, cursor: 'pointer', marginBottom: 4 }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--panel-2)'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
      <div style={{ width: 22, height: 22, borderRadius: 3, background: `color-mix(in srgb, ${colorMap[item.type]} 14%, transparent)`, color: colorMap[item.type], display: 'grid', placeItems: 'center', flex: '0 0 22px' }}>
        <Icon name={item.icon} size={12}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, fontWeight: 500 }}>{item.label}</div>
        <div style={{ fontSize: 10.5, color: 'var(--text-3)', lineHeight: 1.3 }}>{item.desc}</div>
      </div>
      <Icon name="drag" size={11} style={{ color: 'var(--text-4)' }}/>
    </div>
  );
};

const NodeConfig = ({ node }) => {
  const colorMap = { trigger: 'var(--accent)', condition: 'var(--blue)', action: 'var(--green)' };
  return (
    <div>
      <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line)' }}>
        <div className="mono" style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.06em', color: colorMap[node.type] }}>{node.type} · {node.subtype}</div>
        <div style={{ fontSize: 14, fontWeight: 500, marginTop: 4 }}>{node.title}</div>
      </div>
      <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Node label" value={node.title}/>
        {node.subtype === 'Machine event' && (
          <>
            <Field label="Source" value="CNC-04" mono/>
            <Field label="Sensor" value="TC-04 — Spindle temperature" mono/>
            <Field label="Operator" value="greater than" mono/>
            <Field label="Threshold" value="85.0 °C" mono/>
            <Field label="Sustained for" value="30 seconds" mono/>
          </>
        )}
        {node.subtype === 'Notify' && (
          <>
            <Field label="Recipient" value="Maintenance lead (role)"/>
            <Field label="Channels" pills={['SMS','Slack','In-app']}/>
            <Field label="Message template" value="Spindle temperature {{value}}°C on {{machine}}" textarea/>
          </>
        )}
        {node.subtype === 'Create ticket' && (
          <>
            <Field label="Module" value="Maintenance"/>
            <Field label="Priority" value="High"/>
            <Field label="Assign to" value="Auto — round robin"/>
            <Field label="SLA" value="4 hours" mono/>
          </>
        )}
        {(node.subtype === 'If/Else' || node.subtype === 'Threshold') && (
          <>
            <Field label="Condition" value="shift IN ('A','B','C')" mono/>
            <Field label="On true" value="Continue to action branch"/>
            <Field label="On false" value="End workflow"/>
          </>
        )}
        {node.subtype === 'Wait' && (
          <Field label="Duration" value="5 minutes" mono/>
        )}
        {node.subtype === 'Escalate' && (
          <>
            <Field label="Escalate to" value="Plant supervisor"/>
            <Field label="Channels" pills={['SMS','Email','Phone call']}/>
            <Field label="Auto-page" value="If unacknowledged for 5m" mono/>
          </>
        )}

        <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
          <button className="btn primary sm" style={{ flex: 1 }}>Save changes</button>
          <button className="btn sm icon"><Icon name="copy" size={12}/></button>
          <button className="btn sm icon" style={{ color: 'var(--red)' }}><Icon name="trash" size={12}/></button>
        </div>
      </div>
    </div>
  );
};

const Field = ({ label, value, mono, textarea, pills }) => (
  <div>
    <div style={{ fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 5, fontWeight: 500 }}>{label}</div>
    {pills ? (
      <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
        {pills.map(p => <span key={p} className="pill" style={{ textTransform: 'none' }}>{p} <Icon name="x" size={10} style={{ marginLeft: 4 }}/></span>)}
        <button className="btn sm ghost"><Icon name="plus" size={11}/></button>
      </div>
    ) : textarea ? (
      <div style={{ padding: 8, border: '1px solid var(--line)', borderRadius: 4, fontSize: 11.5, fontFamily: mono ? 'JetBrains Mono' : 'inherit', minHeight: 56, background: 'var(--panel-2)' }}>{value}</div>
    ) : (
      <div className={mono ? 'mono' : ''} style={{ padding: '6px 10px', border: '1px solid var(--line)', borderRadius: 4, fontSize: mono ? 11.5 : 12, background: 'var(--panel)' }}>{value}</div>
    )}
  </div>
);

const RunHistory = () => (
  <div className="page-body">
    <div className="card" style={{ overflow: 'hidden' }}>
      <table className="tbl">
        <thead><tr><th>Workflow</th><th>Triggered by</th><th>Status</th><th>Duration</th><th>Started</th><th>Steps</th><th></th></tr></thead>
        <tbody>
          {[
            ['High-temp escalation', 'CNC-04 · spindle', 'completed', '4m 18s', '14:31:02', '6/6'],
            ['Tool wear alert', 'CNC-02 · wear sensor', 'running', '0m 12s', '14:30:55', '2/4'],
            ['Shift handover', 'Schedule · 14:00', 'completed', '0m 04s', '14:00:00', '3/3'],
            ['QA failure routing', 'Form submission', 'failed', '0m 22s', '13:48:11', '2/5'],
            ['Material refill', 'PACK-01', 'completed', '1m 02s', '13:38:30', '4/4'],
            ['Coolant low alert', 'CNC-04', 'completed', '0m 33s', '13:30:18', '3/3'],
            ['Daily OEE report', 'Schedule · 13:00', 'completed', '12s', '13:00:00', '5/5'],
            ['Quality drift escalation', 'ASM-02', 'completed', '2m 40s', '12:14:27', '4/4'],
          ].map((r, i) => (
            <tr key={i}>
              <td style={{ fontWeight: 500 }}>{r[0]}</td>
              <td className="mono" style={{ fontSize: 11.5 }}>{r[1]}</td>
              <td><StatusBadge status={r[2] === 'completed' ? 'resolved' : r[2] === 'running' ? 'investigating' : 'open'}/></td>
              <td className="mono">{r[3]}</td>
              <td className="mono" style={{ fontSize: 11.5 }}>{r[4]}</td>
              <td className="mono">{r[5]}</td>
              <td><button className="btn ghost icon sm"><Icon name="eye" size={12}/></button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

const AllWorkflows = () => (
  <div className="page-body">
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
      {[
        ['High-temp escalation','Active','142 runs/wk','machine telemetry → escalation','var(--accent)'],
        ['Tool wear preventive','Active','68 runs/wk','sensor → maintenance ticket','var(--accent)'],
        ['QA failure routing','Active','28 runs/wk','form submission → CAPA','var(--blue)'],
        ['Shift handover','Active','21 runs/wk','schedule → reports','var(--green)'],
        ['Daily OEE report','Active','7 runs/wk','schedule → email','var(--green)'],
        ['Material refill','Active','94 runs/wk','sensor → ERP webhook','var(--blue)'],
        ['Energy spike alert','Draft','—','telemetry → escalation','var(--text-3)'],
        ['Lot traceability','Active','312 runs/wk','form → record update','var(--blue)'],
        ['Equipment audit','Paused','—','schedule → inspection form','var(--text-3)'],
      ].map((w, i) => (
        <div key={i} className="card">
          <div className="card-header">
            <div className="card-title">{w[0]}</div>
            <span className="pill" style={{ marginLeft: 'auto', color: w[1]==='Active'?'var(--green)':w[1]==='Draft'?'var(--accent)':'var(--text-3)' }}>{w[1]}</span>
          </div>
          <div style={{ padding: 14 }}>
            <div style={{ fontSize: 11.5, color: 'var(--text-2)' }} className="mono">{w[3]}</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, fontSize: 11, color: 'var(--text-3)' }}>
              <span>{w[2]}</span>
              <span>v{Math.floor(Math.random()*5)+1}</span>
            </div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

const TriggersList = () => (
  <div className="page-body">
    <div className="card">
      <table className="tbl">
        <thead><tr><th>Trigger</th><th>Source</th><th>Workflows</th><th>Last fired</th><th>Status</th></tr></thead>
        <tbody>
          {[
            ['Spindle temp > 85°C', 'CNC-04 · TC-04', 'High-temp escalation', '14:31:02', 'active'],
            ['Tool wear > 78%', 'CNC-02 · wear', 'Tool wear preventive', '14:11:38', 'active'],
            ['Shift change · 14:00', 'Schedule', '3 workflows', '14:00:00', 'active'],
            ['QA inspection failed', 'QA Form v4', 'QA failure routing', '13:48:11', 'active'],
            ['Material below 20%', 'PACK-01', 'Material refill', '13:38:30', 'active'],
          ].map((r,i) => <tr key={i}><td className="mono" style={{fontSize:11.5}}>{r[0]}</td><td>{r[1]}</td><td>{r[2]}</td><td className="mono" style={{fontSize:11.5}}>{r[3]}</td><td><span className="pill running"><span className="dot"/>active</span></td></tr>)}
        </tbody>
      </table>
    </div>
  </div>
);

window.WorkflowsPage = WorkflowsPage;
