import React, { useEffect, useState, useCallback } from 'react';
import { useNavigate, useParams } from 'react-router-dom';

const SvgIcon = ({ d, className = '' }: { d: string; className?: string }) => (
  <svg
    className={className}
    fill="none"
    viewBox="0 0 24 24"
    strokeWidth="1.5"
    stroke="currentColor"
  >
    <path strokeLinecap="round" strokeLinejoin="round" d={d} />
  </svg>
);

const IconEye = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178zM15 12a3 3 0 11-6 0 3 3 0 016 0z"
  />
);
const IconMousePointer = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"
  />
);
const IconShoppingCart = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 00-16.536-1.84M7.5 14.25L5.106 5.272M6 20.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm12.75 0a.75.75 0 11-1.5 0 .75.75 0 011.5 0z"
  />
);
const IconPercent = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M9 14.25L15 8.25M10.5 8.25h.008v.008H10.5V8.25zm3.75 6h.008v.008h-.008V14.25z"
  />
);
const IconDollarSign = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M12 6v12m-3-2.818l.879.659c1.171.879 3.07.879 4.242 0 1.172-.879 1.172-2.303 0-3.182C13.536 12.219 12.768 12 12 12c-.725 0-1.45-.22-2.003-.659-1.106-.879-1.106-2.303 0-3.182s2.9-.879 4.006 0l.415.33M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
  />
);
const IconUsers = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
  />
);
const IconTrendingUp = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M2.25 18L9 11.25l4.306 4.307a11.95 11.95 0 015.814-5.519l2.74-1.22m0 0l-5.94-2.28m5.94 2.28l-2.28 5.941"
  />
);
const IconMessageSquare = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M8.625 12a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375M21 12c0 4.556-4.03 8.25-9 8.25a9.764 9.764 0 01-2.555-.337A5.972 5.972 0 015.41 20.97a5.969 5.969 0 01-.474-.065 4.48 4.48 0 00.978-2.025c.09-.457-.133-.901-.467-1.226C3.93 16.178 3 14.189 3 12c0-4.556 4.03-8.25 9-8.25s9 3.694 9 8.25z"
  />
);
const IconClock = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"
  />
);
const IconTarget = ({ className = '' }: { className?: string }) => (
  <svg
    className={className}
    fill="none"
    viewBox="0 0 24 24"
    strokeWidth="1.5"
    stroke="currentColor"
  >
    <circle cx="12" cy="12" r="9" />
    <circle cx="12" cy="12" r="5" />
    <circle cx="12" cy="12" r="1" />
  </svg>
);
const IconThumbsUp = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M6.633 10.5c.806 0 1.533-.446 2.031-1.08a9.041 9.041 0 012.861-2.4c.723-.384 1.35-.956 1.653-1.715a4.498 4.498 0 00.322-1.672V3a.75.75 0 01.75-.75A2.25 2.25 0 0116.5 4.5c0 1.152-.26 2.243-.723 3.218-.266.558.107 1.282.725 1.282h3.126c1.026 0 1.945.694 2.054 1.715.045.422.068.85.068 1.285a11.95 11.95 0 01-2.649 7.521c-.388.482-.987.729-1.605.729H13.48c-.483 0-.964-.078-1.423-.23l-3.114-1.04a4.501 4.501 0 00-1.423-.23H5.904M14.25 9h2.25M5.904 18.75c.083.205.173.405.27.602.197.4-.078.898-.523.898h-.908c-.889 0-1.713-.518-1.972-1.368a12 12 0 01-.521-3.507c0-1.553.295-3.036.831-4.398C3.387 10.203 4.167 9.75 5 9.75h1.053c.472 0 .745.556.5.96a8.958 8.958 0 00-1.302 4.665c0 1.194.232 2.333.654 3.375z"
  />
);
const IconZap = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M3.75 13.5l10.5-11.25L12 10.5h8.25L9.75 21.75 12 13.5H3.75z"
  />
);
const IconHelpCircle = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9 5.25h.008v.008H12v-.008z"
  />
);
const IconAlertTriangle = ({ className = '' }: { className?: string }) => (
  <SvgIcon
    className={className}
    d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
  />
);

import {
  getCampaign,
  updateCampaign,
  deleteCampaign,
  activateCampaign,
  pauseCampaign,
  resumeCampaign,
  completeCampaign,
  previewCampaignProducts,
  getCampaignAnalytics,
  getCampaignConversations,
} from '../service/campaigns/campaigns.service';
import type {
  ICampaign,
  ICampaignMetrics,
  ICampaignJourneyItem,
} from '../service/campaigns/campaigns.interface';
import KPICard from '../components/agent-analytics/KPICard';
import Section from '../components/agent-analytics/Section';
import HBar from '../components/agent-analytics/HBar';
import {
  formatNumber,
  formatDateTime,
  formatIntentScore,
  RECOMAZE_COLORS,
} from '../components/agent-analytics/helpers';
import { getOutcomeBadgeTone } from '../components/agent-analytics/conversationsTab.utils';
import JourneyDetailModal from '../components/agent-analytics/JourneyDetailModal';

const STATUS_COLORS: Record<string, string> = {
  active: 'bg-green-100 text-green-800',
  paused: 'bg-yellow-100 text-yellow-800',
  building: 'bg-blue-100 text-blue-800',
  draft: 'bg-gray-100 text-gray-800',
  completed: 'bg-gray-100 text-gray-800',
  failed: 'bg-red-100 text-red-800',
};

const ANALYTICS_STATUSES = ['active', 'paused', 'completed'];

const SENTIMENT_COLORS = {
  positive: '#22c55e',
  neutral: '#94a3b8',
  negative: '#ef4444',
};

const OUTCOME_COLORS: Record<string, string> = {
  purchase_intent: RECOMAZE_COLORS.primary,
  abandoned: '#ef4444',
  information_only: '#6366f1',
  comparison: '#f59e0b',
  support_resolved: '#22c55e',
  complaint: '#dc2626',
};

const OUTCOME_BADGE_CLASSES: Record<string, string> = {
  success: 'bg-green-100 text-green-800',
  critical: 'bg-red-100 text-red-800',
  warning: 'bg-yellow-100 text-yellow-800',
  info: 'bg-blue-100 text-blue-800',
};

const CampaignDetail = (): JSX.Element => {
  const navigate = useNavigate();
  const { id: campaignId } = useParams<{ id: string }>();

  const [campaign, setCampaign] = useState<ICampaign | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [editPrompt, setEditPrompt] = useState('');
  const [saving, setSaving] = useState(false);

  const [previewCount, setPreviewCount] = useState(0);

  const [analytics, setAnalytics] = useState<ICampaignMetrics | null>(null);
  const [loadingAnalytics, setLoadingAnalytics] = useState(false);

  const [conversations, setConversations] = useState<ICampaignJourneyItem[]>(
    []
  );
  const [nextCursor, setNextCursor] = useState<string | null>(null);
  const [loadingMore, setLoadingMore] = useState(false);
  const [loadingConversations, setLoadingConversations] = useState(false);
  const [selectedFp, setSelectedFp] = useState<string | null>(null);
  const [outcomeFilter, setOutcomeFilter] = useState('');

  const [actionLoading, setActionLoading] = useState<string | null>(null);

  const fetchCampaign = useCallback(async () => {
    if (!campaignId) return;
    try {
      setLoading(true);
      setError(null);
      const response = await getCampaign(campaignId);
      if (!response.errors && response.data) {
        setCampaign(response.data);
        setEditPrompt(response.data.prompt_instruction || '');
      }
    } catch (err: any) {
      setError(err?.message || 'Failed to load campaign');
    } finally {
      setLoading(false);
    }
  }, [campaignId]);

  const fetchPreview = useCallback(async () => {
    if (!campaignId) return;
    try {
      const res = await previewCampaignProducts(campaignId);
      if (!res.errors && res.data) {
        setPreviewCount(res.data.count || 0);
      }
    } catch {
      /* noop */
    }
  }, [campaignId]);

  const fetchAnalytics = useCallback(async () => {
    if (!campaignId || !campaign) return;
    if (!ANALYTICS_STATUSES.includes(campaign.status)) return;
    setLoadingAnalytics(true);
    try {
      const res = await getCampaignAnalytics(campaignId);
      if (!res.errors && res.data) {
        setAnalytics(res.data);
      }
    } catch {
      /* ignore */
    } finally {
      setLoadingAnalytics(false);
    }
  }, [campaignId, campaign?.status]);

  const fetchConversations = useCallback(
    async (cursor?: string | null) => {
      if (!campaignId || !campaign) return;
      if (!ANALYTICS_STATUSES.includes(campaign.status)) return;
      const isLoadMore = !!cursor;
      if (isLoadMore) {
        setLoadingMore(true);
      } else {
        setLoadingConversations(true);
      }
      try {
        const res = await getCampaignConversations(campaignId, 20, cursor);
        if (!res.errors && res.data) {
          if (isLoadMore) {
            setConversations(prev => [...prev, ...(res.data.journeys || [])]);
          } else {
            setConversations(res.data.journeys || []);
          }
          setNextCursor(res.data.next_cursor || null);
        }
      } finally {
        setLoadingMore(false);
        setLoadingConversations(false);
      }
    },
    [campaignId, campaign?.status]
  );

  useEffect(() => {
    fetchCampaign();
  }, [fetchCampaign]);

  // The Reco copilot dispatches ``copilot:data-changed`` after a turn where a
  // write tool ran (pause/resume/complete/update a campaign, etc.). WordPress
  // has no route loaders to revalidate, so this page re-fetches the campaign
  // when the event fires - mirroring the Remix ``revalidator.revalidate()``
  // the copilot used in the Shopify plugin. The listener is removed on unmount.
  useEffect(() => {
    const onCopilotDataChanged = (): void => {
      void fetchCampaign();
    };
    window.addEventListener('copilot:data-changed', onCopilotDataChanged);

    return () => {
      window.removeEventListener('copilot:data-changed', onCopilotDataChanged);
    };
  }, [fetchCampaign]);

  // Poll while campaign is building
  useEffect(() => {
    if (campaign?.status !== 'building') return;

    const interval = setInterval(async () => {
      if (!campaignId) return;
      try {
        const response = await getCampaign(campaignId);
        if (!response.errors && response.data) {
          setCampaign(response.data);
          setEditPrompt(response.data.prompt_instruction || '');
        }
      } catch {
        /* ignore polling errors */
      }
    }, 5000);

    return () => clearInterval(interval);
  }, [campaign?.status, campaignId]);

  useEffect(() => {
    if (campaign) {
      fetchPreview();
      fetchAnalytics();
      fetchConversations();
    }
  }, [campaign?.campaign_id]);

  const handleAction = async (
    action: 'activate' | 'pause' | 'resume' | 'complete' | 'delete'
  ) => {
    if (!campaignId) return;
    const actions = {
      activate: activateCampaign,
      pause: pauseCampaign,
      resume: resumeCampaign,
      complete: completeCampaign,
      delete: deleteCampaign,
    };
    try {
      setActionLoading(action);
      await actions[action](campaignId);
      if (action === 'delete') {
        navigate('/campaigns');
      } else {
        await fetchCampaign();
      }
    } catch (err: any) {
      setError(err?.message || `Failed to ${action} campaign`);
    } finally {
      setActionLoading(null);
    }
  };

  const handleSavePrompt = async () => {
    if (!campaignId) return;
    try {
      setSaving(true);
      const response = await updateCampaign(campaignId, {
        prompt_instruction: editPrompt,
      });
      if (!response.errors && response.data) {
        setCampaign(response.data);
      }
    } catch (err: any) {
      setError(err?.message || 'Failed to save prompt');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="w-full max-w-6xl mx-auto p-5">
        <div className="flex justify-center py-20">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900" />
        </div>
      </div>
    );
  }

  if (!campaign) {
    return (
      <div className="w-full max-w-6xl mx-auto p-5">
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
          <p className="text-sm">{error || 'Campaign not found'}</p>
        </div>
        <div className="mt-4">
          <button
            className="px-4 py-2 bg-white border border-gray-300 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-50"
            onClick={() => navigate('/campaigns')}
          >
            Back to Campaigns
          </button>
        </div>
      </div>
    );
  }

  const hasAnalytics = ANALYTICS_STATUSES.includes(campaign.status);
  const funnelMax = Math.max(analytics?.impressions || 0, 1);
  const conv = analytics?.conversations;
  const sentimentTotal =
    (conv?.sentiment_breakdown?.positive || 0) +
    (conv?.sentiment_breakdown?.neutral || 0) +
    (conv?.sentiment_breakdown?.negative || 0);
  const outcomeEntries = Object.entries(conv?.outcome_distribution || {}).sort(
    (a, b) => b[1] - a[1]
  );
  const outcomeMax = Math.max(...outcomeEntries.map(([, v]) => v), 1);

  const filteredConversations = outcomeFilter
    ? conversations.filter(j => j.outcome === outcomeFilter)
    : conversations;

  return (
    <div className="w-full max-w-6xl mx-auto p-5">
      <div className="space-y-5">
        {/* Header */}
        <div className="flex justify-between items-center flex-wrap gap-3">
          <div className="flex items-center gap-3 flex-wrap">
            <button
              className="px-3 py-1.5 bg-white border border-gray-300 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-50"
              onClick={() => navigate('/campaigns')}
            >
              Back
            </button>
            <h1 className="text-xl font-bold text-gray-900">{campaign.name}</h1>
            <span
              className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[campaign.status] || 'bg-gray-100 text-gray-800'}`}
            >
              {campaign.status}
            </span>
            <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
              {campaign.priority}
            </span>
          </div>
          <div className="flex items-center gap-2">
            {campaign.status === 'draft' && (
              <button
                className="px-3 py-1.5 text-sm font-medium bg-gray-900 text-white rounded-lg hover:bg-gray-800 disabled:opacity-50"
                disabled={actionLoading === 'activate'}
                onClick={() => handleAction('activate')}
              >
                {actionLoading === 'activate' ? '...' : 'Activate'}
              </button>
            )}
            {campaign.status === 'active' && (
              <button
                className="px-3 py-1.5 text-sm font-medium bg-white border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 disabled:opacity-50"
                disabled={actionLoading === 'pause'}
                onClick={() => handleAction('pause')}
              >
                {actionLoading === 'pause' ? '...' : 'Pause'}
              </button>
            )}
            {campaign.status === 'paused' && (
              <button
                className="px-3 py-1.5 text-sm font-medium bg-gray-900 text-white rounded-lg hover:bg-gray-800 disabled:opacity-50"
                disabled={actionLoading === 'resume'}
                onClick={() => handleAction('resume')}
              >
                {actionLoading === 'resume' ? '...' : 'Resume'}
              </button>
            )}
            {['active', 'paused'].includes(campaign.status) && (
              <button
                className="px-3 py-1.5 text-sm font-medium bg-white border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 disabled:opacity-50"
                disabled={actionLoading === 'complete'}
                onClick={() => handleAction('complete')}
              >
                {actionLoading === 'complete' ? '...' : 'Complete'}
              </button>
            )}
            {['draft', 'failed', 'completed'].includes(campaign.status) && (
              <button
                className="px-3 py-1.5 text-sm font-medium bg-white border border-red-300 text-red-600 rounded-lg hover:bg-red-50 disabled:opacity-50"
                disabled={actionLoading === 'delete'}
                onClick={() => handleAction('delete')}
              >
                {actionLoading === 'delete' ? '...' : 'Delete'}
              </button>
            )}
          </div>
        </div>

        {error && (
          <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg flex justify-between items-center">
            <p className="text-sm">{error}</p>
            <button
              className="text-red-500 hover:text-red-700 text-sm"
              onClick={() => setError(null)}
            >
              Dismiss
            </button>
          </div>
        )}

        {/* Campaign info */}
        <div className="bg-white rounded-xl border border-gray-200 p-5 space-y-3">
          <div className="flex items-center gap-3 flex-wrap">
            <span className="text-sm text-gray-500">Categories:</span>
            {campaign.target_categories.map(cat => (
              <span
                key={cat}
                className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700"
              >
                {cat}
              </span>
            ))}
          </div>
          {campaign.description && (
            <p className="text-sm text-gray-700">{campaign.description}</p>
          )}
          <div className="flex items-center gap-2 flex-wrap">
            {campaign.goal && (
              <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
                {campaign.goal}
              </span>
            )}
            {campaign.tone_of_voice && (
              <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                {campaign.tone_of_voice.split(' - ')[0]}
              </span>
            )}
            {(campaign.min_price || campaign.max_price) && (
              <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                Price: {campaign.min_price ? `${campaign.min_price}` : '0'} -{' '}
                {campaign.max_price ? `${campaign.max_price}` : '\u221E'}
              </span>
            )}
          </div>
          {campaign.discount_codes && campaign.discount_codes.length > 0 && (
            <div className="space-y-1">
              <span className="text-sm text-gray-500">Discount codes:</span>
              <div className="flex items-center gap-2 flex-wrap">
                {campaign.discount_codes.map(dc => (
                  <span
                    key={dc.code}
                    className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800"
                  >
                    {dc.code} (
                    {dc.type === 'percentage' ? `${dc.value}%` : dc.value}) ·{' '}
                    {dc.used_count}/{dc.max_uses || '\u221E'}
                  </span>
                ))}
              </div>
            </div>
          )}
          <div className="flex items-center gap-4 flex-wrap">
            {campaign.indexed_product_count > 0 && (
              <span className="text-sm text-gray-500">
                {campaign.indexed_product_count} products indexed
              </span>
            )}
            {previewCount > 0 && (
              <span className="text-sm text-gray-500">
                {previewCount} matching products
              </span>
            )}
            {campaign.created_at && (
              <span className="text-sm text-gray-500">
                Created:{' '}
                {new Date(campaign.created_at).toLocaleDateString('en-US', {
                  month: 'short',
                  day: 'numeric',
                  year: 'numeric',
                })}
              </span>
            )}
          </div>
        </div>

        {/* Analytics */}
        {hasAnalytics && (
          <>
            {loadingAnalytics ? (
              <div className="flex justify-center py-8">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900" />
              </div>
            ) : analytics ? (
              <>
                {/* Product Performance KPIs */}
                <h2 className="text-base font-semibold text-gray-900">
                  Product Performance
                </h2>
                <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
                  <KPICard
                    icon={IconEye}
                    label="Impressions"
                    value={formatNumber(analytics.impressions ?? 0)}
                    tooltip="Times campaign products were shown in chat"
                  />
                  <KPICard
                    icon={IconMousePointer}
                    label="Clicks"
                    value={formatNumber(analytics.clicks ?? 0)}
                    tooltip="Clicks on campaign product cards"
                  />
                  <KPICard
                    icon={IconShoppingCart}
                    label="Add to Cart"
                    value={formatNumber(analytics.add_to_cart ?? 0)}
                    tooltip="Products added to cart from campaign"
                  />
                  <KPICard
                    icon={IconPercent}
                    label="CTR"
                    value={`${analytics.ctr ?? 0}%`}
                    tooltip="Click-through rate"
                  />
                  <KPICard
                    icon={IconTrendingUp}
                    label="Conv. Rate"
                    value={`${analytics.conversion_rate ?? 0}%`}
                    tooltip="Add to cart / clicks"
                  />
                  <KPICard
                    icon={IconDollarSign}
                    label="Cart Value"
                    value={`$${(analytics.cart_value ?? 0).toFixed(2)}`}
                    tooltip="Total value of campaign products added to cart"
                  />
                </div>

                {/* Campaign Funnel + Cart Value */}
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  <Section
                    title="Product Funnel"
                    tooltip="Progression from impression to add-to-cart"
                  >
                    <HBar
                      label="Impressions"
                      value={analytics.impressions ?? 0}
                      max={funnelMax}
                      color={RECOMAZE_COLORS.primary}
                    />
                    <HBar
                      label="Clicks"
                      value={analytics.clicks ?? 0}
                      max={funnelMax}
                      color={RECOMAZE_COLORS.accent1}
                    />
                    <HBar
                      label="Add to Cart"
                      value={analytics.add_to_cart ?? 0}
                      max={funnelMax}
                      color={RECOMAZE_COLORS.dark}
                    />
                  </Section>

                  <Section
                    title="Cart Value"
                    tooltip="Revenue generated by campaign"
                  >
                    <div className="flex items-center gap-3 mb-4">
                      <div className="w-12 h-12 rounded-xl bg-[#ffeef8] flex items-center justify-center">
                        <IconDollarSign className="w-6 h-6 text-[#B7007C]" />
                      </div>
                      <span className="text-3xl font-bold text-gray-900">
                        ${(analytics.cart_value || 0).toFixed(2)}
                      </span>
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <p className="text-sm text-gray-500">Avg per Click</p>
                        <p className="text-base font-bold text-gray-900">
                          $
                          {(analytics.clicks ?? 0) > 0
                            ? (
                                (analytics.cart_value ?? 0) / analytics.clicks
                              ).toFixed(2)
                            : '0.00'}
                        </p>
                      </div>
                      <div>
                        <p className="text-sm text-gray-500">Avg per Session</p>
                        <p className="text-base font-bold text-gray-900">
                          $
                          {(analytics.unique_sessions ?? 0) > 0
                            ? (
                                (analytics.cart_value ?? 0) /
                                analytics.unique_sessions
                              ).toFixed(2)
                            : '0.00'}
                        </p>
                      </div>
                    </div>
                  </Section>
                </div>

                {/* Conversation Analytics KPIs */}
                {conv && conv.total_conversations > 0 && (
                  <>
                    <hr className="border-gray-200" />
                    <h2 className="text-base font-semibold text-gray-900">
                      Conversation Analytics
                    </h2>
                    <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
                      <KPICard
                        icon={IconMessageSquare}
                        label="Conversations"
                        value={formatNumber(conv.total_conversations ?? 0)}
                        tooltip="Conversations where campaign products were shown"
                      />
                      <KPICard
                        icon={IconUsers}
                        label="Sessions"
                        value={formatNumber(analytics.unique_sessions ?? 0)}
                        tooltip="Unique chat sessions"
                      />
                      <KPICard
                        icon={IconClock}
                        label="Avg Duration"
                        value={`${conv.avg_duration_minutes ?? 0}m`}
                        tooltip="Average conversation duration"
                      />
                      <KPICard
                        icon={IconTarget}
                        label="Avg Intent"
                        value={`${((conv.avg_intent_score ?? 0) * 100).toFixed(0)}%`}
                        tooltip="Average purchase intent score"
                      />
                      <KPICard
                        icon={IconThumbsUp}
                        label="Satisfaction"
                        value={`${conv.satisfaction_rate ?? 0}%`}
                        tooltip="Rate of positive feedback"
                      />
                      <KPICard
                        icon={IconZap}
                        label="High Intent"
                        value={formatNumber(
                          conv.high_intent_conversations ?? 0
                        )}
                        tooltip="Conversations with high purchase intent (>=70%)"
                      />
                    </div>

                    {/* Conversation details row */}
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                      {/* Sentiment breakdown */}
                      <Section
                        title="Sentiment Breakdown"
                        tooltip="Customer sentiment during campaign conversations"
                      >
                        {sentimentTotal > 0 ? (
                          <>
                            <div className="flex gap-1 h-6 rounded-full overflow-hidden mb-3">
                              {(
                                ['positive', 'neutral', 'negative'] as const
                              ).map(s => {
                                const val = conv.sentiment_breakdown[s] || 0;
                                const pct = (val / sentimentTotal) * 100;
                                if (pct === 0) return null;
                                return (
                                  <div
                                    key={s}
                                    style={{
                                      width: `${pct}%`,
                                      backgroundColor: SENTIMENT_COLORS[s],
                                    }}
                                    className="transition-all duration-500"
                                  />
                                );
                              })}
                            </div>
                            <div className="flex gap-4">
                              {(
                                ['positive', 'neutral', 'negative'] as const
                              ).map(s => (
                                <div
                                  key={s}
                                  className="flex items-center gap-1"
                                >
                                  <div
                                    className="w-3 h-3 rounded-full"
                                    style={{
                                      backgroundColor: SENTIMENT_COLORS[s],
                                    }}
                                  />
                                  <span className="text-sm text-gray-700">
                                    {s}: {conv.sentiment_breakdown[s] || 0}
                                  </span>
                                </div>
                              ))}
                            </div>
                          </>
                        ) : (
                          <p className="text-sm text-gray-500">
                            No sentiment data yet
                          </p>
                        )}
                      </Section>

                      {/* Outcome distribution */}
                      <Section
                        title="Conversation Outcomes"
                        tooltip="How campaign conversations ended"
                      >
                        {outcomeEntries.length > 0 ? (
                          outcomeEntries.map(([outcome, count]) => (
                            <HBar
                              key={outcome}
                              label={outcome.replace(/_/g, ' ')}
                              value={count}
                              max={outcomeMax}
                              color={
                                OUTCOME_COLORS[outcome] ||
                                RECOMAZE_COLORS.accent1
                              }
                            />
                          ))
                        ) : (
                          <p className="text-sm text-gray-500">
                            No outcome data yet
                          </p>
                        )}
                      </Section>
                    </div>

                    {/* Extra stats row */}
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                      <Section>
                        <p className="text-sm text-gray-500">
                          Avg Messages/Conv
                        </p>
                        <p className="text-lg font-bold text-gray-900">
                          {conv.avg_messages ?? 0}
                        </p>
                      </Section>
                      <Section>
                        <p className="text-sm text-gray-500">Avg Duration</p>
                        <p className="text-lg font-bold text-gray-900">
                          {conv.avg_duration_minutes ?? 0}{' '}
                          <span className="text-sm font-normal">min</span>
                        </p>
                      </Section>
                      <Section>
                        <p className="text-sm text-gray-500">
                          High Intent Rate
                        </p>
                        <p className="text-lg font-bold text-gray-900">
                          {conv.high_intent_rate ?? 0}%
                        </p>
                      </Section>
                      <Section>
                        <p className="text-sm text-gray-500">
                          Satisfaction Rate
                        </p>
                        <p className="text-lg font-bold text-gray-900">
                          {conv.satisfaction_rate ?? 0}%
                        </p>
                      </Section>
                    </div>

                    {/* Questions & Pain Points */}
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                      {conv.top_questions && conv.top_questions.length > 0 && (
                        <Section
                          title="Common Questions"
                          tooltip="Most frequent questions asked during campaign conversations"
                        >
                          <div className="space-y-2">
                            {conv.top_questions.map((q, i) => (
                              <div
                                key={i}
                                className="flex items-start gap-3 py-2 border-b border-gray-100 last:border-0"
                              >
                                <div className="w-6 h-6 rounded-full bg-[#ffeef8] flex items-center justify-center flex-shrink-0 mt-0.5">
                                  <IconHelpCircle className="w-3 h-3 text-[#B7007C]" />
                                </div>
                                <div className="flex-1">
                                  <p className="text-sm text-gray-700">
                                    {q.question}
                                  </p>
                                </div>
                                <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
                                  {q.count}x
                                </span>
                              </div>
                            ))}
                          </div>
                        </Section>
                      )}

                      {conv.top_pain_points &&
                        conv.top_pain_points.length > 0 && (
                          <Section
                            title="Pain Points"
                            tooltip="Issues customers raised during campaign conversations"
                          >
                            <div className="space-y-2">
                              {conv.top_pain_points.map((pp, i) => (
                                <div
                                  key={i}
                                  className="flex items-start gap-3 py-2 border-b border-gray-100 last:border-0"
                                >
                                  <div className="w-6 h-6 rounded-full bg-red-50 flex items-center justify-center flex-shrink-0 mt-0.5">
                                    <IconAlertTriangle className="w-3 h-3 text-red-500" />
                                  </div>
                                  <div className="flex-1">
                                    <p className="text-sm text-gray-700">
                                      {pp.issue}
                                    </p>
                                  </div>
                                  <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
                                    {pp.count}x
                                  </span>
                                </div>
                              ))}
                            </div>
                          </Section>
                        )}
                    </div>
                  </>
                )}

                {/* Top Products */}
                {analytics.top_products &&
                  analytics.top_products.length > 0 && (
                    <>
                      <hr className="border-gray-200" />
                      <Section
                        title="Top Campaign Products"
                        tooltip="Best performing products in this campaign"
                      >
                        <div className="space-y-2">
                          {analytics.top_products.slice(0, 10).map((p, i) => (
                            <div
                              key={p.sku}
                              className="flex items-center justify-between py-2 border-b border-gray-100 last:border-0"
                            >
                              <div className="flex items-center gap-3">
                                <div
                                  className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold text-white"
                                  style={{
                                    backgroundColor: RECOMAZE_COLORS.primary,
                                  }}
                                >
                                  {i + 1}
                                </div>
                                <span className="text-sm font-semibold text-gray-900">
                                  {p.name}
                                </span>
                              </div>
                              <div className="flex items-center gap-4">
                                <span className="text-sm text-gray-500">
                                  {p.impressions} views
                                </span>
                                <span className="text-sm text-gray-500">
                                  {p.clicks} clicks
                                </span>
                                <span className="text-sm text-gray-500">
                                  {p.add_to_cart} cart
                                </span>
                              </div>
                            </div>
                          ))}
                        </div>
                      </Section>
                    </>
                  )}
              </>
            ) : (
              <div className="bg-white rounded-xl border border-gray-200 p-6">
                <p className="text-sm text-gray-500">
                  No analytics data yet. Data appears after visitors interact
                  with campaign products.
                </p>
              </div>
            )}
          </>
        )}

        {/* Conversations */}
        {hasAnalytics && (
          <>
            <hr className="border-gray-200" />
            <h2 className="text-base font-semibold text-gray-900">
              Campaign Conversations
            </h2>
            {loadingConversations ? (
              <div className="flex justify-center py-8">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900" />
              </div>
            ) : conversations.length === 0 ? (
              <div className="bg-white rounded-xl border border-gray-200 p-6">
                <p className="text-sm text-gray-500">
                  No conversations found for this campaign yet.
                </p>
              </div>
            ) : (
              <>
                <div className="bg-white rounded-xl border border-gray-200 p-5 space-y-4">
                  <div className="flex justify-between items-center">
                    <h3 className="text-sm font-semibold text-gray-900">
                      {outcomeFilter
                        ? `${filteredConversations.length} of ${conversations.length}`
                        : `${conversations.length}`}{' '}
                      Conversations
                    </h3>
                    <select
                      className="border border-gray-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
                      value={outcomeFilter}
                      onChange={e => setOutcomeFilter(e.target.value)}
                    >
                      <option value="">All outcomes</option>
                      <option value="purchase_intent">Purchase intent</option>
                      <option value="abandoned">Abandoned</option>
                      <option value="information_only">Information only</option>
                      <option value="comparison">Comparison</option>
                      <option value="support_resolved">Support resolved</option>
                    </select>
                  </div>
                  <div className="overflow-x-auto">
                    <table className="w-full text-sm">
                      <thead>
                        <tr className="border-b border-gray-200">
                          <th className="text-left py-2 px-2 font-medium text-gray-500">
                            Date
                          </th>
                          <th className="text-right py-2 px-2 font-medium text-gray-500">
                            Duration
                          </th>
                          <th className="text-right py-2 px-2 font-medium text-gray-500">
                            Messages
                          </th>
                          <th className="text-left py-2 px-2 font-medium text-gray-500">
                            Outcome
                          </th>
                          <th className="text-right py-2 px-2 font-medium text-gray-500">
                            Intent
                          </th>
                          <th className="text-right py-2 px-2 font-medium text-gray-500">
                            Clicks
                          </th>
                          <th className="text-right py-2 px-2 font-medium text-gray-500">
                            Carts
                          </th>
                          <th className="text-left py-2 px-2 font-medium text-gray-500">
                            Stage
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        {filteredConversations.map(j => (
                          <tr
                            key={j.fingerprint}
                            className="border-b border-gray-100 cursor-pointer hover:bg-[#ffeef8] transition-colors"
                            onClick={() => setSelectedFp(j.fingerprint)}
                          >
                            <td className="py-2 px-2 text-gray-700">
                              {formatDateTime(j.first_message_at)}
                            </td>
                            <td className="py-2 px-2 text-right text-gray-700">
                              {j.duration_minutes != null
                                ? `${j.duration_minutes.toFixed(1)}m`
                                : '-'}
                            </td>
                            <td className="py-2 px-2 text-right text-gray-700">
                              {j.message_count || 0}
                            </td>
                            <td className="py-2 px-2">
                              <span
                                className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${OUTCOME_BADGE_CLASSES[getOutcomeBadgeTone(j.outcome)] || 'bg-blue-100 text-blue-800'}`}
                              >
                                {j.outcome || '-'}
                              </span>
                            </td>
                            <td className="py-2 px-2 text-right text-gray-700">
                              {formatIntentScore(j.purchase_intent_score)}
                            </td>
                            <td className="py-2 px-2 text-right text-gray-700">
                              {j.product_clicks || 0}
                            </td>
                            <td className="py-2 px-2 text-right text-gray-700">
                              {j.add_to_cart_count || 0}
                            </td>
                            <td className="py-2 px-2">
                              {j.last_stage ? (
                                <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
                                  {j.last_stage}
                                </span>
                              ) : (
                                '-'
                              )}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                  <p className="text-xs text-gray-500">
                    Click a row to view conversation details
                  </p>
                  {nextCursor && (
                    <div className="flex justify-center">
                      <button
                        className="px-4 py-2 bg-white border border-gray-300 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-50 disabled:opacity-50"
                        disabled={loadingMore}
                        onClick={() => fetchConversations(nextCursor)}
                      >
                        {loadingMore ? 'Loading...' : 'Load More'}
                      </button>
                    </div>
                  )}
                </div>

                {selectedFp && (
                  <JourneyDetailModal
                    fingerprint={selectedFp}
                    onClose={() => setSelectedFp(null)}
                  />
                )}
              </>
            )}
          </>
        )}

        <hr className="border-gray-200" />

        {/* Prompt editor */}
        <Section title="Campaign Sales Rules (AI-generated, editable)">
          <div className="space-y-3">
            <textarea
              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-gray-900/20 focus:border-gray-400"
              value={editPrompt}
              onChange={e => setEditPrompt(e.target.value)}
              rows={8}
            />
            <div className="flex justify-end">
              <button
                className="px-4 py-2 bg-gray-900 text-white text-sm font-medium rounded-lg hover:bg-gray-800 disabled:opacity-50"
                disabled={saving}
                onClick={handleSavePrompt}
              >
                {saving ? 'Saving...' : 'Save Prompt'}
              </button>
            </div>
          </div>
        </Section>
      </div>
    </div>
  );
};

export default CampaignDetail;
