// ============================================================
// MOORE AI v13 — PIPELINE TAB
// Requires: shared/utils.js, shared/components.jsx loaded first
// ============================================================

const PipelineView = ({ crmData, filteredOpps, pipelines, pipelineView, setPipelineView, pipelineFilter, setPipelineFilter, setSelectedLead, updateOppStatus, searchQuery, setSearchQuery, syncOpportunities, dragItemRef, selectedPipelineId, setSelectedPipelineId }) => {
  const { useMemo } = React;

  const pipelineOptions = useMemo(() => {
    const opts = [];
    if (pipelines && pipelines.length > 0) {
      pipelines.forEach(p => opts.push({ id: p.id, name: p.name }));
    } else {
      const seen = {};
      filteredOpps.forEach(o => {
        if (o.pipelineId && !seen[o.pipelineId]) {
          seen[o.pipelineId] = true;
          opts.push({ id: o.pipelineId, name: o.pipelineName || `Pipeline ${Object.keys(seen).length}` });
        }
      });
    }
    return opts;
  }, [pipelines, filteredOpps]);

  const handlePipelineChange = (id) => {
    setSelectedPipelineId(id);
    syncOpportunities(id);
  };

  const statusFilteredOpps = useMemo(() => {
    if (pipelineFilter === 'all') return filteredOpps;
    return filteredOpps.filter(o => o.status === pipelineFilter);
  }, [filteredOpps, pipelineFilter]);

  const stages = useMemo(() => {
    const stageMap = {};
    const stageOrder = [];
    const oppsForStages = statusFilteredOpps.filter(o => o.status !== 'won' && o.status !== 'lost');
    oppsForStages.forEach(o => {
      const key = o.stageName || 'Prospect';
      if (!stageMap[key]) {
        stageMap[key] = { name: key, id: o.stageId || key, opps: [], total: 0 };
        stageOrder.push(key);
      }
      stageMap[key].opps.push(o);
      stageMap[key].total += Number(o.value) || 0;
    });
    return stageOrder.map(k => stageMap[k]);
  }, [statusFilteredOpps]);

  const stageColors = ['#3b82f6', '#8b5cf6', '#06b6d4', '#10b981', '#f59e0b', '#ec4899', '#f97316'];
  const wonOpps = filteredOpps.filter(o => o.status === 'won');
  const lostOpps = filteredOpps.filter(o => o.status === 'lost');

  return (
    <div className="h-full flex flex-col">
      {/* Toolbar */}
      <div className="flex items-center justify-between px-6 py-4 border-b border-slate-800/50 shrink-0 bg-[#030712]/50 flex-wrap gap-3">
        <div className="flex items-center gap-3 flex-wrap">
          <h2 className="font-black text-white text-xl italic tracking-tight">Pipeline</h2>
          {pipelineOptions.length > 0 && (
            <div className="relative">
              <select value={selectedPipelineId} onChange={e => handlePipelineChange(e.target.value)}
                className="bg-slate-900/80 border border-slate-700/60 rounded-xl px-3 py-1.5 text-xs font-bold text-slate-300 outline-none focus:border-blue-500/50 cursor-pointer appearance-none pr-7"
                style={{ backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2'%3E%3Cpath d='M6 9l6 6 6-6'/%3E%3C/svg%3E")`, backgroundRepeat: 'no-repeat', backgroundPosition: 'right 8px center' }}>
                <option value="">All Pipelines</option>
                {pipelineOptions.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
            </div>
          )}
          <div className="flex items-center gap-1 bg-slate-900/60 border border-slate-800 rounded-xl p-1">
            {['all', 'open', 'won', 'lost'].map(f => (
              <button key={f} onClick={() => setPipelineFilter(f)}
                className={`px-3 py-1.5 rounded-lg text-xs font-bold mono uppercase transition-all ${pipelineFilter === f ? 'bg-blue-600 text-white' : 'text-slate-500 hover:text-white'}`}>
                {f}
              </button>
            ))}
          </div>
        </div>
        <div className="flex items-center gap-2">
          <div className="relative">
            <i data-lucide="search" style={{width:12,height:12}} className="inline-block absolute left-3 top-1/2 -translate-y-1/2 text-slate-600"></i>
            <input value={searchQuery} onChange={e => setSearchQuery(e.target.value)}
              placeholder="Search leads..."
              className="bg-slate-900/60 border border-slate-800 rounded-lg pl-8 pr-3 py-1.5 text-xs text-slate-300 outline-none focus:border-blue-500/50 w-44 placeholder:text-slate-700" />
          </div>
          <div className="flex items-center gap-1 bg-slate-900/60 border border-slate-800 rounded-xl p-1">
            {[['kanban', 'layout-grid'], ['list', 'list']].map(([v, icon]) => (
              <button key={v} onClick={() => setPipelineView(v)}
                className={`px-2.5 py-1.5 rounded-lg transition-all ${pipelineView === v ? 'bg-slate-700 text-white' : 'text-slate-600 hover:text-white'}`}>
                <i data-lucide={icon} style={{width:14,height:14}} className="inline-block"></i>
              </button>
            ))}
          </div>
          <button onClick={() => syncOpportunities(selectedPipelineId)} className="flex items-center gap-1.5 px-3 py-1.5 bg-blue-600/10 border border-blue-500/20 rounded-xl text-xs font-bold text-blue-400 hover:bg-blue-600/20 transition-all">
            <i data-lucide="refresh-cw" style={{width:12,height:12}} className="inline-block"></i> Refresh
          </button>
        </div>
      </div>

      {/* Stats row */}
      <div className="flex items-center gap-6 px-6 py-2.5 border-b border-slate-800/30 bg-[#030712]/30 text-xs mono text-slate-600 shrink-0">
        <span><span className="text-white font-bold">{filteredOpps.length}</span> total</span>
        <span><span className="text-blue-400 font-bold">{filteredOpps.filter(o=>o.status==='open').length}</span> open</span>
        <span><span className="text-emerald-400 font-bold">{wonOpps.length}</span> won</span>
        <span><span className="text-red-400 font-bold">{lostOpps.length}</span> lost</span>
        {selectedPipelineId && pipelineOptions.length > 0 && (
          <span className="text-slate-600">— <span className="text-slate-400">{pipelineOptions.find(p=>p.id===selectedPipelineId)?.name || 'Selected Pipeline'}</span></span>
        )}
        <span className="ml-auto text-slate-500">Value: <span className="text-white font-bold">{fmt$(filteredOpps.reduce((a,o)=>a+Number(o.value||0),0))}</span></span>
      </div>

      {/* Content */}
      {pipelineView === 'kanban' ? (
        <div className="flex-1 overflow-x-auto overflow-y-hidden">
          <div className="flex gap-4 h-full p-5" style={{ minWidth: Math.max(stages.length + (pipelineFilter === 'all' ? 2 : 1), 2) * 290 + 40 }}>
            {stages.map((stage, si) => (
              <div key={stage.name} className="flex flex-col shrink-0 kanban-col bg-slate-900/30 border border-slate-800/60 rounded-2xl overflow-hidden" style={{width: 272}}>
                <div className="px-4 py-3 border-b flex items-center justify-between" style={{ borderColor: stageColors[si % stageColors.length] + '40' }}>
                  <div>
                    <div className="font-bold text-white text-sm flex items-center gap-2">
                      <div className="w-2 h-2 rounded-full shrink-0" style={{ background: stageColors[si % stageColors.length] }} />
                      {stage.name}
                    </div>
                    <div className="text-[10px] mono text-slate-600 mt-0.5 ml-4">{stage.opps.length} deals · {fmt$(stage.total)}</div>
                  </div>
                </div>
                <div className="flex-1 overflow-y-auto p-2.5 space-y-2">
                  {stage.opps.map(opp => (
                    <div key={opp.id} onClick={() => setSelectedLead(opp)}
                      className="bg-[#0d1424] border border-slate-800/70 rounded-xl p-3 cursor-pointer hover:border-slate-600/70 hover:bg-slate-900/60 transition-all group">
                      <div className="flex items-center gap-2 mb-2.5">
                        <Avatar name={opp.name} size={28} />
                        <div className="flex-1 min-w-0">
                          <div className="text-sm font-bold text-white truncate group-hover:text-blue-300 transition-colors leading-tight">{opp.name}</div>
                          <div className="text-[10px] text-slate-600 truncate">{opp.contact}</div>
                        </div>
                      </div>
                      <div className="flex items-center justify-between">
                        <StatusBadge status={opp.status} />
                        <div className="font-black mono text-sm text-white">{fmt$(opp.value)}</div>
                      </div>
                    </div>
                  ))}
                  {stage.opps.length === 0 && <div className="py-6 text-center text-[10px] mono text-slate-800 uppercase tracking-widest">Empty</div>}
                </div>
              </div>
            ))}

            {(pipelineFilter === 'all' || pipelineFilter === 'won') && (
              <div className="flex flex-col shrink-0 bg-emerald-950/20 border border-emerald-800/20 rounded-2xl overflow-hidden" style={{width: 272}}>
                <div className="px-4 py-3 border-b border-emerald-800/20">
                  <div className="font-bold text-emerald-400 text-sm flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-emerald-500 shrink-0" /> Closed Won
                  </div>
                  <div className="text-[10px] mono text-slate-600 mt-0.5 ml-4">{wonOpps.length} deals · {fmt$(wonOpps.reduce((a,o)=>a+Number(o.value||0),0))}</div>
                </div>
                <div className="flex-1 overflow-y-auto p-2.5 space-y-2">
                  {wonOpps.length === 0
                    ? <div className="py-6 text-center text-[10px] mono text-slate-800 uppercase tracking-widest">No won deals</div>
                    : wonOpps.map(opp => (
                      <div key={opp.id} onClick={() => setSelectedLead(opp)}
                        className="bg-emerald-950/30 border border-emerald-900/30 rounded-xl p-3 cursor-pointer hover:border-emerald-700/40 transition-all">
                        <div className="text-sm font-bold text-emerald-300 leading-tight truncate">{opp.name}</div>
                        <div className="text-[10px] text-slate-600 mt-0.5">{opp.contact}</div>
                        <div className="mono text-sm font-black text-white mt-1.5">{fmt$(opp.value)}</div>
                      </div>
                    ))}
                </div>
              </div>
            )}

            {(pipelineFilter === 'all' || pipelineFilter === 'lost') && (
              <div className="flex flex-col shrink-0 bg-red-950/10 border border-red-900/15 rounded-2xl overflow-hidden" style={{width: 272}}>
                <div className="px-4 py-3 border-b border-red-900/15">
                  <div className="font-bold text-red-400/80 text-sm flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-red-500/70 shrink-0" /> Closed Lost
                  </div>
                  <div className="text-[10px] mono text-slate-600 mt-0.5 ml-4">{lostOpps.length} deals</div>
                </div>
                <div className="flex-1 overflow-y-auto p-2.5 space-y-2">
                  {lostOpps.length === 0
                    ? <div className="py-6 text-center text-[10px] mono text-slate-800 uppercase tracking-widest">No lost deals</div>
                    : lostOpps.map(opp => (
                      <div key={opp.id} onClick={() => setSelectedLead(opp)}
                        className="bg-red-950/20 border border-red-900/20 rounded-xl p-3 cursor-pointer hover:border-red-700/30 transition-all">
                        <div className="text-sm font-bold text-red-400/80 leading-tight truncate">{opp.name}</div>
                        <div className="text-[10px] text-slate-600 mt-0.5">{opp.contact}</div>
                        <div className="mono text-sm font-bold text-slate-400 mt-1.5">{fmt$(opp.value)}</div>
                      </div>
                    ))}
                </div>
              </div>
            )}
          </div>
        </div>
      ) : (
        <div className="flex-1 overflow-y-auto p-6">
          <div className="bg-slate-900/40 border border-slate-800/60 rounded-2xl overflow-hidden">
            <table className="w-full">
              <thead>
                <tr className="border-b border-slate-800/50">
                  {['Deal Name', 'Contact', 'Stage', 'Value', 'Status', 'Source', ''].map((h, i) => (
                    <th key={i} className="text-left px-5 py-3 text-[10px] mono text-slate-600 uppercase tracking-[0.15em] font-bold">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {statusFilteredOpps.map(opp => (
                  <tr key={opp.id} onClick={() => setSelectedLead(opp)}
                    className="border-b border-slate-800/30 data-row cursor-pointer transition-colors">
                    <td className="px-5 py-4">
                      <div className="flex items-center gap-3">
                        <Avatar name={opp.name} size={32} />
                        <div className="font-bold text-white text-sm">{opp.name}</div>
                      </div>
                    </td>
                    <td className="px-5 py-4 text-sm text-slate-400">{opp.contact}</td>
                    <td className="px-5 py-4 text-xs mono text-slate-500">{opp.stageName || '—'}</td>
                    <td className="px-5 py-4 font-bold mono text-white text-sm">{fmt$(opp.value)}</td>
                    <td className="px-5 py-4"><StatusBadge status={opp.status} /></td>
                    <td className="px-5 py-4 text-xs text-slate-600">{opp.source}</td>
                    <td className="px-5 py-4"><i data-lucide="chevron-right" style={{width:14,height:14}} className="inline-block text-slate-700"></i></td>
                  </tr>
                ))}
              </tbody>
            </table>
            {statusFilteredOpps.length === 0 && (
              <div className="py-16 text-center text-xs mono text-slate-700 uppercase tracking-widest">
                {filteredOpps.length === 0 ? 'No deals in this pipeline — try Refresh' : 'No records match filter'}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};
