import React, { useState, useEffect, useCallback } from 'react';
import { useAuth } from '../../auth/AuthProvider';
import {
  listInitiatives, getInitiative, updateInitiativeStatus,
  listChannelCampaigns, launchInitiative, getBilling
} from '../../services/initiativeApi';
import { listWizards, deleteWizard } from '../../services/wizardApi';

/* ─── Status mapping ─── */
const STATUS_MAP = {
  draft:          { label: 'Draft',         css: 'status-draft',         color: 'gray' },
  staged:         { label: 'Ready to Launch', css: 'status-staged',      color: 'blue' },
  pending:        { label: 'Launching',     css: 'status-pending',       color: 'blue' },
  submitted:      { label: 'In Review',     css: 'status-in-review',     color: 'blue' },
  pending_review: { label: 'In Review',     css: 'status-in-review',     color: 'blue' },
  in_review:      { label: 'In Review',     css: 'status-in-review',     color: 'blue' },
  active:         { label: 'Active',        css: 'status-active',        color: 'green' },
  paused:         { label: 'Paused',        css: 'status-paused',        color: 'orange' },
  completed:      { label: 'Completed',     css: 'status-completed',     color: 'gray' },
  cancelled:      { label: 'Cancelled',     css: 'status-cancelled',     color: 'red' },
  error:          { label: 'Action Needed', css: 'status-action-needed', color: 'red' },
};

const IN_REVIEW_STATUSES = ['submitted', 'pending_review', 'in_review'];

function getDisplayStatus(initiative) {
  const raw = (initiative.iniStatus || initiative.status || 'draft').toLowerCase();
  if (raw === 'staged') {
    const start = initiative.iniStartDate || initiative.startDate;
    if (start && new Date(start) > new Date()) {
      return { label: 'Scheduled', css: 'status-scheduled', color: 'blue' };
    }
  }
  return STATUS_MAP[raw] || STATUS_MAP.draft;
}

function getRawStatus(initiative) {
  return (initiative.iniStatus || initiative.status || 'draft').toLowerCase();
}

function isInReview(raw) {
  return IN_REVIEW_STATUSES.includes(raw);
}

function getId(init) {
  return init.iniInitiativeId || init.initiativeId || init.id;
}

/* ─── Filter tabs ─── */
const FILTER_TABS = [
  { key: 'all',        label: 'All' },
  { key: 'active',     label: 'Active' },
  { key: 'in_review',  label: 'In Review' },
  { key: 'staged',     label: 'Ready' },
  { key: 'paused',     label: 'Paused' },
  { key: 'completed',  label: 'Completed' },
];

const FILTER_MAP = {
  'active':    ['active'],
  'in_review': ['submitted', 'pending_review', 'in_review', 'pending'],
  'staged':    ['staged'],
  'paused':    ['paused'],
  'completed': ['completed', 'cancelled'],
};

/* ─── Helpers ─── */
const fmtBudget = (v) => {
  const n = parseFloat(v);
  if (!n || isNaN(n)) return '$0';
  return n >= 1000 ? `$${(n / 1000).toFixed(n % 1000 === 0 ? 0 : 1)}k` : `$${n.toFixed(0)}`;
};

const fmtDate = (d) => {
  if (!d) return '—';
  return new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
};

const timeAgo = (dateStr) => {
  if (!dateStr) return '';
  const diff = Math.floor((Date.now() - new Date(dateStr).getTime()) / 1000);
  if (diff < 60) return 'just now';
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  return `${Math.floor(diff / 86400)}d ago`;
};

const objectiveLabel = (obj) => {
  if (!obj) return 'Campaign';
  const map = {
    awareness: 'Brand Awareness', traffic: 'Website Traffic',
    leads: 'Lead Generation', sales: 'Sales', conversions: 'Conversions',
  };
  return map[obj.toLowerCase()] || obj.charAt(0).toUpperCase() + obj.slice(1);
};

const channelLabel = (ch) => {
  const map = { google_ads: 'Google Ads', google: 'Google Ads', meta: 'Meta', tiktok: 'TikTok' };
  return map[(ch || '').toLowerCase()] || ch;
};

/* ─── Icons ─── */
const I = {
  search: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>,
  calendar: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>,
  dollar: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>,
  play: <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5,3 19,12 5,21"/></svg>,
  pause: <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>,
  rocket: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 00-2.91-.09z"/><path d="M12 15l-3-3a22 22 0 012-3.95A12.88 12.88 0 0122 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 01-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>,
  eye: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>,
  copy: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>,
  alert: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>,
  pencil: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>,
  plus: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>,
  close: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  chart: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>,
  x: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>,
  check: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="20 6 9 17 4 12"/></svg>,
  clock: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>,
};


/* ═══════════════════════════════════════════════════
   Launch Confirmation Modal
   ═══════════════════════════════════════════════════ */
function LaunchModal({ initiative, billing, loading, onConfirm, onCancel }) {
  const name = initiative?.iniName || initiative?.name || 'Campaign';
  const budget = parseFloat(initiative?.iniBudget || initiative?.totalBudget || 0);

  return (
    <div className="modal-overlay" onClick={onCancel}>
      <div className="modal-content launch-modal" onClick={e => e.stopPropagation()}>
        <div className="launch-modal-header">
          <div className="launch-modal-icon">{I.rocket}</div>
          <h3>Launch Campaign</h3>
          <p>Ready to go live with <strong>{name}</strong>?</p>
        </div>

        {billing && (
          <div className="launch-modal-billing">
            <div className="billing-row">
              <span>Ad Spend</span>
              <span>{fmtBudget(billing.adSpend || budget)}/mo</span>
            </div>
            {billing.managementFee > 0 && (
              <div className="billing-row">
                <span>Management Fee</span>
                <span>{fmtBudget(billing.managementFee)}/mo</span>
              </div>
            )}
            <div className="billing-row billing-total">
              <span>Total Monthly</span>
              <span>{fmtBudget(billing.totalCharge || budget)}/mo</span>
            </div>
          </div>
        )}

        {!billing && (
          <div className="launch-modal-billing">
            <div className="billing-row billing-total">
              <span>Monthly Budget</span>
              <span>{fmtBudget(budget)}/mo</span>
            </div>
          </div>
        )}

        <div className="launch-modal-actions">
          <button className="btn btn-outline" onClick={onCancel} disabled={loading}>Cancel</button>
          <button className="btn btn-primary btn-launch" onClick={onConfirm} disabled={loading}>
            {loading ? (
              <><span className="mini-spinner" /> Launching…</>
            ) : (
              <>{I.rocket} Launch Now</>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}


/* ═══════════════════════════════════════════════════
   Detail Panel (slide-in)
   ═══════════════════════════════════════════════════ */
function DetailPanel({ initiative, channels, onClose, onAction, actionLoading }) {
  if (!initiative) return null;

  const ds = getDisplayStatus(initiative);
  const raw = getRawStatus(initiative);
  const budget = parseFloat(initiative.iniBudget || initiative.totalBudget || 0);
  const id = getId(initiative);
  const reviewStatus = isInReview(raw);

  return (
    <div className="detail-panel-overlay" onClick={onClose}>
      <div className="detail-panel" onClick={e => e.stopPropagation()}>
        <div className="detail-panel-header">
          <div>
            <h3>{initiative.iniName || initiative.name || 'Untitled'}</h3>
            <span className={`status-badge ${ds.css}`}>{ds.label}</span>
          </div>
          <button className="btn btn-ghost btn-icon" onClick={onClose}>{I.close}</button>
        </div>

        <div className="detail-panel-body">
          {/* In Review notice */}
          {reviewStatus && (
            <div className="detail-notice notice-info">
              <span className="notice-icon">{I.clock}</span>
              <div>
                <strong>Under Review</strong>
                <p>This campaign has been submitted to the ad network and is awaiting approval. This typically takes 24–48 hours.</p>
              </div>
            </div>
          )}

          {/* Overview */}
          <section className="detail-section">
            <h4>Overview</h4>
            <div className="detail-grid">
              <div className="detail-item">
                <span className="detail-label">Objective</span>
                <span className="detail-value">{objectiveLabel(initiative.iniObjective || initiative.objective)}</span>
              </div>
              <div className="detail-item">
                <span className="detail-label">Budget</span>
                <span className="detail-value">{fmtBudget(budget)}/{initiative.iniBudgetPeriod || initiative.budgetPeriod || 'month'}</span>
              </div>
              <div className="detail-item">
                <span className="detail-label">Start Date</span>
                <span className="detail-value">{fmtDate(initiative.iniStartDate || initiative.startDate)}</span>
              </div>
              <div className="detail-item">
                <span className="detail-label">End Date</span>
                <span className="detail-value">{fmtDate(initiative.iniEndDate || initiative.endDate)}</span>
              </div>
            </div>
          </section>

          {/* Channel Allocation */}
          {channels && channels.length > 0 && (
            <section className="detail-section">
              <h4>Channel Allocation</h4>
              <div className="channel-allocation-list">
                {channels.map((ch, i) => {
                  const alloc = parseFloat(ch.chcAllocPct || ch.allocPct || 0);
                  const chBudget = budget * (alloc / 100);
                  const chStatus = (ch.chcStatus || ch.status || '').toLowerCase();
                  const chDs = STATUS_MAP[chStatus] || STATUS_MAP.pending;
                  return (
                    <div key={i} className="channel-alloc-row">
                      <div className="channel-alloc-info">
                        <span className="channel-alloc-name">{channelLabel(ch.chcChannel || ch.channel)}</span>
                        <span className={`status-badge-sm ${chDs.css}`}>{chDs.label}</span>
                        <span className="channel-alloc-budget">{fmtBudget(chBudget)}</span>
                      </div>
                      <div className="channel-alloc-bar-track">
                        <div className="channel-alloc-bar" style={{ width: `${Math.min(alloc, 100)}%` }} />
                      </div>
                      <span className="channel-alloc-pct">{alloc.toFixed(0)}%</span>
                    </div>
                  );
                })}
              </div>
            </section>
          )}

          {/* Timeline */}
          <section className="detail-section">
            <h4>Timeline</h4>
            <div className="detail-timeline">
              <div className="timeline-item">
                <span className="timeline-dot created" />
                <span>Created {fmtDate(initiative.iniCreatedAt || initiative.createdAt)}</span>
              </div>
              {reviewStatus && (
                <div className="timeline-item">
                  <span className="timeline-dot submitted" />
                  <span>Submitted for review</span>
                </div>
              )}
              {(raw === 'active' || raw === 'paused' || raw === 'completed') && (
                <div className="timeline-item">
                  <span className="timeline-dot launched" />
                  <span>Launched {fmtDate(initiative.iniStartDate || initiative.startDate)}</span>
                </div>
              )}
              {raw === 'completed' && (
                <div className="timeline-item">
                  <span className="timeline-dot completed" />
                  <span>Completed {fmtDate(initiative.iniEndDate || initiative.endDate)}</span>
                </div>
              )}
            </div>
          </section>

          {/* Actions */}
          <section className="detail-section">
            <div className="detail-actions">
              {raw === 'staged' && (
                <>
                  <button
                    className="btn btn-primary"
                    onClick={() => onAction('launch', initiative)}
                    disabled={actionLoading === id}
                  >
                    {I.rocket} Launch Campaign
                  </button>
                  <button
                    className="btn btn-ghost"
                    onClick={() => onAction('cancel', initiative)}
                    disabled={actionLoading === id}
                  >
                    {I.x} Cancel
                  </button>
                </>
              )}
              {reviewStatus && (
                <button
                  className="btn btn-outline btn-danger-outline"
                  onClick={() => onAction('cancel', initiative)}
                  disabled={actionLoading === id}
                >
                  {I.x} Cancel Campaign
                </button>
              )}
              {raw === 'active' && (
                <button className="btn btn-outline" onClick={() => onAction('pause', initiative)}>
                  {I.pause} Pause Campaign
                </button>
              )}
              {raw === 'paused' && (
                <button className="btn btn-primary" onClick={() => onAction('resume', initiative)}>
                  {I.play} Resume Campaign
                </button>
              )}
              {(raw === 'completed' || raw === 'cancelled') && (
                <button className="btn btn-outline" onClick={() => onAction('duplicate', initiative)}>
                  {I.copy} Duplicate Campaign
                </button>
              )}
              {raw === 'error' && (
                <button className="btn btn-primary" onClick={() => onAction('resolve', initiative)}>
                  {I.alert} Resolve Issue
                </button>
              )}
            </div>
          </section>
        </div>
      </div>
    </div>
  );
}


/* ═══════════════════════════════════════════════════
   Main Campaigns Component
   ═══════════════════════════════════════════════════ */
export default function Campaigns({ onNavigate }) {
  const { sessionToken } = useAuth();
  const [initiatives, setInitiatives] = useState([]);
  const [drafts, setDrafts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [activeFilter, setActiveFilter] = useState('all');
  const [search, setSearch] = useState('');
  const [selectedInit, setSelectedInit] = useState(null);
  const [selectedChannels, setSelectedChannels] = useState([]);
  const [actionLoading, setActionLoading] = useState(null);

  // Launch modal
  const [launchTarget, setLaunchTarget] = useState(null);
  const [launchBilling, setLaunchBilling] = useState(null);
  const [launching, setLaunching] = useState(false);

  /* ─── Data loading ─── */
  const loadData = useCallback(async () => {
    setLoading(true);
    try {
      const [initRes, draftRes] = await Promise.all([
        listInitiatives(sessionToken),
        listWizards(sessionToken, 'draft', 20),
      ]);

      if (initRes.ok) {
        const list = initRes.data?.data || initRes.data?.initiatives || [];
        setInitiatives(Array.isArray(list) ? list : []);
      }
      if (draftRes.ok) {
        const list = draftRes.data?.data || draftRes.data || [];
        setDrafts(Array.isArray(list) ? list : []);
      }
    } catch (e) {
      console.error('Failed to load campaigns:', e);
    }
    setLoading(false);
  }, [sessionToken]);

  useEffect(() => {
    if (sessionToken) loadData();
  }, [sessionToken, loadData]);

  /* ─── Open detail panel ─── */
  const openDetail = async (init) => {
    setSelectedInit(init);
    const id = getId(init);
    if (id) {
      const chRes = await listChannelCampaigns(id, sessionToken);
      if (chRes.ok) {
        const list = chRes.data?.data || chRes.data?.channels || [];
        setSelectedChannels(Array.isArray(list) ? list : []);
      }
    }
  };

  const closeDetail = () => {
    setSelectedInit(null);
    setSelectedChannels([]);
  };

  /* ─── Launch flow ─── */
  const startLaunch = async (init) => {
    const id = getId(init);
    setLaunchTarget(init);
    setLaunchBilling(null);

    try {
      const billingRes = await getBilling(id, sessionToken);
      if (billingRes.ok && billingRes.data?.billing) {
        setLaunchBilling(billingRes.data.billing);
      }
    } catch (e) {
      // Billing fetch is optional
    }
  };

  const confirmLaunch = async () => {
    if (!launchTarget) return;
    const id = getId(launchTarget);
    setLaunching(true);

    try {
      const res = await launchInitiative(id, sessionToken);
      if (res.ok || res.data?.channels) {
        setLaunchTarget(null);
        closeDetail();
        await loadData();
      } else {
        alert(res.error || res.data?.error || 'Launch failed');
      }
    } catch (e) {
      alert('Launch error: ' + e.message);
    }

    setLaunching(false);
  };

  const cancelLaunch = () => {
    setLaunchTarget(null);
    setLaunchBilling(null);
  };

  /* ─── Actions ─── */
  const handleAction = async (action, init) => {
    const id = getId(init);
    setActionLoading(id);

    try {
      if (action === 'launch') {
        setActionLoading(null);
        startLaunch(init);
        return;
      } else if (action === 'pause') {
        await updateInitiativeStatus(id, 'paused', sessionToken);
        await loadData();
        closeDetail();
      } else if (action === 'resume') {
        await updateInitiativeStatus(id, 'active', sessionToken);
        await loadData();
        closeDetail();
      } else if (action === 'cancel') {
        if (window.confirm('Cancel this campaign? This action cannot be undone.')) {
          await updateInitiativeStatus(id, 'cancelled', sessionToken);
          await loadData();
          closeDetail();
        }
      } else if (action === 'duplicate') {
        onNavigate?.('wizard', { duplicateFrom: id });
      } else if (action === 'resolve') {
        openDetail(init);
      }
    } catch (e) {
      console.error(`Action ${action} failed:`, e);
    }
    setActionLoading(null);
  };

  const continueDraft = (draft) => {
    const wizId = draft.wizWizardId || draft.wizardId || draft.id;
    onNavigate?.('wizard', { wizardId: wizId });
  };

  const removeDraft = async (e, draft) => {
    e.stopPropagation();
    const wizId = draft.wizWizardId || draft.wizardId || draft.id;
    if (wizId && window.confirm('Delete this draft?')) {
      await deleteWizard(wizId, sessionToken);
      await loadData();
    }
  };

  /* ─── Filtering ─── */
  const filteredInitiatives = initiatives.filter(init => {
    const raw = getRawStatus(init);

    if (activeFilter !== 'all') {
      if (!FILTER_MAP[activeFilter]?.includes(raw)) return false;
    }

    if (search) {
      const q = search.toLowerCase();
      const name = (init.iniName || init.name || '').toLowerCase();
      const obj = (init.iniObjective || init.objective || '').toLowerCase();
      const ds = getDisplayStatus(init);
      if (!name.includes(q) && !obj.includes(q) && !ds.label.toLowerCase().includes(q)) return false;
    }

    return true;
  });

  /* ─── Tab counts ─── */
  const tabCounts = {};
  FILTER_TABS.forEach(t => {
    if (t.key === 'all') {
      tabCounts[t.key] = initiatives.length;
    } else {
      tabCounts[t.key] = initiatives.filter(i => FILTER_MAP[t.key]?.includes(getRawStatus(i))).length;
    }
  });

  /* ─── Render ─── */
  if (loading) {
    return (
      <div className="view-container">
        <div style={{ textAlign: 'center', padding: '60px 0', color: 'var(--color-text-muted)' }}>
          Loading campaigns…
        </div>
      </div>
    );
  }

  return (
    <div className="view-container">
      {/* Header */}
      <div className="view-header">
        <div>
          <h2>Campaigns</h2>
          <p className="text-muted">Manage your advertising campaigns across all channels</p>
        </div>
        <button className="btn btn-primary" onClick={() => onNavigate?.('wizard')}>
          {I.plus} New Campaign
        </button>
      </div>

      {/* Draft Section */}
      {drafts.length > 0 && (
        <div style={{ marginBottom: '24px' }}>
          <h4 style={{ fontSize: '13px', fontWeight: 600, color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: '0.5px', marginBottom: '10px' }}>
            Drafts ({drafts.length})
          </h4>
          <div className="draft-cards">
            {drafts.map((d, i) => (
              <div key={i} className="draft-card" onClick={() => continueDraft(d)}>
                <span style={{ fontSize: '20px' }}>{I.pencil}</span>
                <div className="draft-info">
                  <span style={{ fontWeight: 600, fontSize: '13px' }}>
                    {d.wizName || d.name || `Draft ${i + 1}`}
                  </span>
                  <span style={{ fontSize: '12px', color: 'var(--color-text-muted)' }}>
                    {timeAgo(d.wizUpdatedAt || d.updatedAt)}
                  </span>
                </div>
                <button
                  className="btn btn-ghost btn-icon"
                  onClick={(e) => removeDraft(e, d)}
                  title="Delete draft"
                  style={{ marginLeft: 'auto', fontSize: '12px', opacity: 0.5 }}
                >×</button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ─── Toolbar: Filter Tabs + Search ─── */}
      <div className="campaigns-toolbar">
        <div className="filter-tabs">
          {FILTER_TABS.map(tab => {
            const count = tabCounts[tab.key] || 0;
            const isActive = activeFilter === tab.key;
            if (count === 0 && tab.key !== 'all' && !isActive) return null;
            return (
              <button
                key={tab.key}
                className={`filter-tab${isActive ? ' active' : ''}`}
                onClick={() => setActiveFilter(tab.key)}
              >
                {tab.label}
                {count > 0 && <span className="tab-count">{count}</span>}
              </button>
            );
          })}
        </div>
        <div className="search-box">
          <span className="search-icon">{I.search}</span>
          <input
            type="text"
            className="search-input"
            placeholder="Search campaigns…"
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
          {search && (
            <button className="search-clear" onClick={() => setSearch('')}>{I.x}</button>
          )}
        </div>
      </div>

      {/* Campaign Cards */}
      {filteredInitiatives.length === 0 ? (
        <div className="campaigns-empty">
          <div className="campaigns-empty-icon">{I.chart}</div>
          <p className="campaigns-empty-title">
            {initiatives.length === 0 ? 'No campaigns yet' : 'No campaigns match your filters'}
          </p>
          <p className="campaigns-empty-sub">
            {initiatives.length === 0
              ? 'Create your first campaign to get started.'
              : 'Try adjusting your search or filter.'
            }
          </p>
        </div>
      ) : (
        <div className="campaign-cards">
          {filteredInitiatives.map((init, i) => {
            const ds = getDisplayStatus(init);
            const raw = getRawStatus(init);
            const id = getId(init);
            const budget = parseFloat(init.iniBudget || init.totalBudget || 0);
            const channels = init.channels || init.channelSummary || [];
            const reviewStatus = isInReview(raw);

            return (
              <div key={id || i} className="campaign-card" onClick={() => openDetail(init)}>
                <div className="campaign-card-header">
                  <span className="campaign-card-title">
                    {init.iniName || init.name || 'Untitled Campaign'}
                  </span>
                  <span className={`status-badge ${ds.css}`}>{ds.label}</span>
                </div>

                <div className="campaign-card-body">
                  <div className="campaign-card-meta">
                    <span>{I.dollar} {fmtBudget(budget)}/{init.iniBudgetPeriod || init.budgetPeriod || 'monthly'}</span>
                    <span>{I.calendar} {fmtDate(init.iniStartDate || init.startDate)}</span>
                    {(init.iniObjective || init.objective) && (
                      <span>{objectiveLabel(init.iniObjective || init.objective)}</span>
                    )}
                  </div>

                  {/* Channel pills */}
                  {Array.isArray(channels) && channels.length > 0 && (
                    <div className="campaign-card-channels">
                      {channels.map((ch, j) => {
                        const chName = typeof ch === 'string' ? ch : (ch.chcChannel || ch.channel || ch.name);
                        const pct = typeof ch === 'object' ? (ch.chcAllocPct || ch.allocPct) : null;
                        return (
                          <span key={j} className="channel-pill">
                            {channelLabel(chName)}
                            {pct ? ` ${parseFloat(pct).toFixed(0)}%` : ''}
                          </span>
                        );
                      })}
                    </div>
                  )}

                  {/* Action buttons — context-aware per status */}
                  <div className="campaign-card-actions">
                    {raw === 'draft' && (
                      <button className="btn btn-sm btn-outline" onClick={e => { e.stopPropagation(); continueDraft(init); }}>
                        {I.pencil} Continue
                      </button>
                    )}
                    {raw === 'staged' && (
                      <>
                        <button
                          className="btn btn-sm btn-primary"
                          onClick={e => { e.stopPropagation(); handleAction('launch', init); }}
                          disabled={actionLoading === id}
                        >
                          {I.rocket} Launch
                        </button>
                        <button
                          className="btn btn-sm btn-ghost"
                          onClick={e => { e.stopPropagation(); handleAction('cancel', init); }}
                        >
                          {I.x} Cancel
                        </button>
                      </>
                    )}
                    {reviewStatus && (
                      <>
                        <button className="btn btn-sm btn-outline" onClick={e => { e.stopPropagation(); openDetail(init); }}>
                          {I.eye} View Details
                        </button>
                        <button className="btn btn-sm btn-ghost" onClick={e => { e.stopPropagation(); handleAction('cancel', init); }}>
                          {I.x} Cancel
                        </button>
                      </>
                    )}
                    {raw === 'active' && (
                      <>
                        <button className="btn btn-sm btn-outline" onClick={e => { e.stopPropagation(); openDetail(init); }}>
                          {I.chart} Performance
                        </button>
                        <button className="btn btn-sm btn-ghost" onClick={e => { e.stopPropagation(); handleAction('pause', init); }}>
                          {I.pause} Pause
                        </button>
                      </>
                    )}
                    {raw === 'paused' && (
                      <button className="btn btn-sm btn-primary" onClick={e => { e.stopPropagation(); handleAction('resume', init); }}>
                        {I.play} Resume
                      </button>
                    )}
                    {raw === 'pending' && (
                      <button className="btn btn-sm btn-outline" onClick={e => { e.stopPropagation(); openDetail(init); }}>
                        {I.eye} View Details
                      </button>
                    )}
                    {(raw === 'completed' || raw === 'cancelled') && (
                      <button className="btn btn-sm btn-outline" onClick={e => { e.stopPropagation(); handleAction('duplicate', init); }}>
                        {I.copy} Duplicate
                      </button>
                    )}
                    {raw === 'error' && (
                      <button className="btn btn-sm btn-primary" onClick={e => { e.stopPropagation(); handleAction('resolve', init); }}>
                        {I.alert} Resolve
                      </button>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Detail Panel */}
      {selectedInit && (
        <DetailPanel
          initiative={selectedInit}
          channels={selectedChannels}
          onClose={closeDetail}
          onAction={handleAction}
          actionLoading={actionLoading}
        />
      )}

      {/* Launch Confirmation Modal */}
      {launchTarget && (
        <LaunchModal
          initiative={launchTarget}
          billing={launchBilling}
          loading={launching}
          onConfirm={confirmLaunch}
          onCancel={cancelLaunch}
        />
      )}
    </div>
  );
}
