import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
  Typography,
  Card,
  Tag,
  Row,
  Col,
  Spin,
  Empty,
  Statistic,
  Result,
  Button,
  Input,
  Avatar,
  Space,
  Divider,
  Drawer,
  Grid,
  Tooltip,
  Popover,
  Pagination,
  message,
  theme,
} from 'antd';
import {
  MailOutlined,
  MessageOutlined,
  StarFilled,
  SearchOutlined,
  UserOutlined,
  PhoneOutlined,
  GlobalOutlined,
  ArrowRightOutlined,
  CopyOutlined,
  SendOutlined,
  EditOutlined,
  EnvironmentOutlined,
  BankOutlined,
} from '@ant-design/icons';
import axios from 'axios';
import { useSettingsStore } from '@/stores/settings.store';
import { useAuthStore } from '@/stores/auth.store';
import { usePageAds } from '@/hooks/usePageAds';
import AdBanner from '@/components/AdBanner';
import AuthModal from '@/components/AuthModal';
import type { Campaign, GovernmentLevel, Representative, RepresentativeLookupResponse } from '@/types/api';
import { GOVERNMENT_LEVEL_COLORS, GOVERNMENT_LEVEL_LABELS } from '@/types/api';
import { groupRepsByLevel, GOVERNMENT_LEVEL_DISPLAY_COLORS } from '@/utils/representatives';
import { isTrending, isNew } from '@/utils/badges';
import { usePostalCode } from '@/hooks/usePostalCode';

const { Title, Text, Paragraph } = Typography;

export default function CampaignsListPage() {
  const [campaigns, setCampaigns] = useState<Campaign[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const { token } = theme.useToken();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { settings: siteSettings } = useSettingsStore();
  const { isAuthenticated } = useAuthStore();
  const navigate = useNavigate();
  const [authModalOpen, setAuthModalOpen] = useState(false);
  const campaignListAds = usePageAds('campaigns_list');

  // Derive colors from theme tokens (set by PublicLayout from settings)
  const colorPrimary = token.colorPrimary;
  const colorBgContainer = token.colorBgContainer;
  const headerGradient = siteSettings?.publicHeaderGradient ?? `linear-gradient(135deg, ${colorPrimary} 0%, ${token.colorPrimaryBgHover} 100%)`;

  // Rep lookup state — persisted across pages
  const { postalCode, setPostalCode } = usePostalCode();
  const [postalCodeInput, setPostalCodeInput] = useState(postalCode);
  const [lookupLoading, setLookupLoading] = useState(false);
  const [representatives, setRepresentatives] = useState<Representative[] | null>(null);
  const [lookupLocation, setLookupLocation] = useState<{ city: string | null; province: string | null } | null>(null);

  // Campaign selector drawer (mobile)
  const [campaignDrawerOpen, setCampaignDrawerOpen] = useState(false);

  useEffect(() => {
    document.title = `Campaigns | ${siteSettings?.organizationName || 'Changemaker'}`;
  }, [siteSettings?.organizationName]);

  useEffect(() => {
    fetchCampaigns();
  }, [page]); // eslint-disable-line react-hooks/exhaustive-deps

  const fetchCampaigns = async () => {
    setLoading(true);
    setError(false);
    try {
      const { data } = await axios.get('/api/campaigns/public', { params: { page, limit: 20 } });
      setCampaigns(data.campaigns);
      setTotal(data.pagination.total);
    } catch {
      setError(true);
    } finally {
      setLoading(false);
    }
  };

  const handleLookup = async () => {
    if (!postalCodeInput.trim()) {
      message.warning('Please enter your postal code');
      return;
    }
    setLookupLoading(true);
    try {
      const code = postalCodeInput.replace(/\s/g, '').toUpperCase();
      const { data } = await axios.get<RepresentativeLookupResponse>(
        `/api/representatives/by-postal/${code}`
      );
      setRepresentatives(data.representatives);
      setLookupLocation(data.location);
      // Persist postal code on successful lookup
      setPostalCode(code);
    } catch {
      message.error('Could not look up representatives for this postal code');
    } finally {
      setLookupLoading(false);
    }
  };

  const navigateToCampaign = (slug: string) => {
    const pc = postalCodeInput.replace(/\s/g, '').toUpperCase();
    navigate(`/campaign/${slug}?postalCode=${pc}`);
  };

  const navigateToCreate = () => {
    if (isAuthenticated) {
      navigate('/campaigns/create');
    } else {
      setAuthModalOpen(true);
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 80 }}>
        <Spin size="large" />
      </div>
    );
  }

  if (error) {
    return (
      <Result
        status="500"
        title="Failed to Load Campaigns"
        subTitle="There was an error loading campaigns. Please try again later."
        extra={
          <Button type="primary" onClick={fetchCampaigns}>
            Retry
          </Button>
        }
      />
    );
  }

  const featured = campaigns.filter(c => c.highlightCampaign);
  const nonFeatured = campaigns.filter(c => !c.highlightCampaign);

  // Group representatives by government level
  const repsByLevel = representatives ? groupRepsByLevel(representatives) : null;
  const locationText = lookupLocation
    ? [lookupLocation.city, lookupLocation.province].filter(Boolean).join(', ')
    : '';

  // Campaign selector content (shared between Popover desktop + Drawer mobile)
  const campaignSelectorContent = (
    <div>
      {campaigns.map((c) => (
        <Card
          key={c.id}
          hoverable
          size="small"
          style={{
            marginBottom: 8,
            cursor: 'pointer',
            borderRadius: 8,
          }}
          styles={{ body: { padding: '12px 14px' } }}
          onClick={() => {
            setCampaignDrawerOpen(false);
            navigateToCampaign(c.slug);
          }}
        >
          <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2 }}>
            <SendOutlined style={{ marginRight: 6, fontSize: 12, opacity: 0.6 }} />
            {c.title}
          </div>
          {c.description && (
            <div style={{
              fontSize: 13,
              opacity: 0.6,
              lineHeight: 1.4,
              display: '-webkit-box',
              WebkitLineClamp: 2,
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              marginLeft: 18,
            }}>
              {c.description}
            </div>
          )}
        </Card>
      ))}
      {campaigns.length > 0 && <Divider style={{ margin: '12px 0' }} />}
      <Card
        hoverable
        size="small"
        style={{
          cursor: 'pointer',
          borderRadius: 8,
          borderStyle: 'dashed',
        }}
        styles={{ body: { padding: '14px', textAlign: 'center' } }}
        onClick={() => {
          setCampaignDrawerOpen(false);
          navigateToCreate();
        }}
      >
        <EditOutlined style={{ marginRight: 6, fontSize: 14 }} />
        <span style={{ fontWeight: 600, fontSize: 14 }}>Write Your Own Campaign</span>
        <div style={{ fontSize: 12, opacity: 0.55, marginTop: 4 }}>
          Create a custom message for this issue
        </div>
      </Card>
    </div>
  );

  return (
    <div>
      {/* Hero Banner */}
      <div
        style={{
          textAlign: 'center',
          padding: isMobile ? '36px 16px 32px' : '48px 24px 40px',
          marginBottom: 32,
          background: headerGradient,
          borderRadius: 12,
          position: 'relative',
          overflow: 'hidden',
        }}
      >
        <Title level={2} style={{ color: '#fff', margin: 0, fontSize: isMobile ? 26 : 32, textShadow: '0 2px 4px rgba(0,0,0,0.2)' }}>
          {siteSettings?.organizationName ?? 'Changemaker Lite'}
        </Title>
        <Paragraph style={{ color: 'rgba(255,255,255,0.85)', fontSize: isMobile ? 15 : 16, margin: '12px 0 0' }}>
          Connect with your elected representatives across all levels of government
        </Paragraph>
      </div>

      {/* Find Your Representatives Section */}
      <div style={{ marginBottom: 32 }}>
        <Title level={3} style={{ color: '#fff', textAlign: 'center', marginBottom: 16 }}>
          Find Your Representatives
        </Title>
        <Card
          style={{
            background: colorBgContainer,
            border: '1px solid rgba(255,255,255,0.1)',
            borderRadius: 12,
            maxWidth: 600,
            margin: '0 auto',
          }}
        >
          <Text style={{ color: 'rgba(255,255,255,0.7)', display: 'block', textAlign: 'center', marginBottom: 12, fontSize: isMobile ? 15 : 14 }}>
            Enter your postal code:
          </Text>
          <div style={{ display: 'flex', gap: 12, flexDirection: !screens.sm ? 'column' : 'row' }}>
            <Input
              placeholder="e.g. T5K 2M5"
              value={postalCodeInput}
              onChange={(e) => setPostalCodeInput(e.target.value)}
              onPressEnter={handleLookup}
              size="large"
              aria-label="Postal code"
              style={{ textTransform: 'uppercase', flex: screens.sm ? 1 : undefined }}
              disabled={lookupLoading}
              prefix={lookupLoading ? <Spin size="small" /> : undefined}
            />
            <Button
              type="primary"
              size="large"
              icon={<SearchOutlined />}
              onClick={handleLookup}
              loading={lookupLoading}
              block={!screens.sm}
            >
              Search
            </Button>
          </div>
        </Card>

        {/* Representative Results */}
        {repsByLevel && (
          <div style={{ marginTop: 24 }}>
            {locationText && (
              <Card
                size="small"
                style={{
                  background: `linear-gradient(135deg, ${token.colorPrimaryBg} 0%, ${colorBgContainer} 100%)`,
                  border: '1px solid rgba(255,255,255,0.1)',
                  borderRadius: 10,
                  marginBottom: 20,
                  textAlign: 'center',
                }}
              >
                <EnvironmentOutlined style={{ marginRight: 6, color: token.colorPrimary }} />
                <Text style={{ color: 'rgba(255,255,255,0.75)', fontSize: isMobile ? 15 : 14 }}>
                  Showing representatives for <Text strong style={{ color: '#fff' }}>{locationText}</Text>
                </Text>
              </Card>
            )}
            {representatives!.length === 0 ? (
              <Result
                status="info"
                title="No Representatives Found"
                subTitle="No representatives were found for this postal code."
              />
            ) : (
              Object.entries(repsByLevel).map(([level, reps]) => (
                <div key={level} style={{ marginBottom: 28 }}>
                  <Title level={4} style={{ color: GOVERNMENT_LEVEL_DISPLAY_COLORS[level] || '#94a3b8', marginBottom: 14, fontSize: isMobile ? 18 : 20 }}>
                    {GOVERNMENT_LEVEL_LABELS[level as GovernmentLevel] || level} Representatives
                  </Title>
                  <Space direction="vertical" size={16} style={{ width: '100%' }}>
                    {reps.map((rep, idx) => (
                      <RepCard
                        key={rep.id || idx}
                        rep={rep}
                        isMobile={isMobile}
                        token={token}
                        colorBgContainer={colorBgContainer}
                        campaigns={campaigns}
                        onOpenDrawer={() => setCampaignDrawerOpen(true)}
                        campaignSelectorContent={campaignSelectorContent}
                      />
                    ))}
                  </Space>
                </div>
              ))
            )}
          </div>
        )}
      </div>

      {/* Campaign Selection Drawer (Mobile) */}
      <Drawer
        title={campaigns.length > 0 ? 'Choose a Campaign' : 'Take Action'}
        placement="bottom"
        open={campaignDrawerOpen}
        onClose={() => setCampaignDrawerOpen(false)}
        height="auto"
        styles={{
          body: { padding: 16, maxHeight: '70vh', overflowY: 'auto' },
        }}
      >
        {campaignSelectorContent}
      </Drawer>

      <Divider style={{ borderColor: 'rgba(255,255,255,0.08)' }} />

      {/* Featured Campaign */}
      {featured.map((campaign) => (
        <div key={campaign.id} style={{ marginBottom: 24 }}>
          <Link to={`/campaign/${campaign.slug}`} style={{ display: 'block' }}>
            <Card
              hoverable
              style={{
                background: `linear-gradient(135deg, ${colorBgContainer} 0%, ${token.colorPrimaryBg} 100%)`,
                border: '1px solid rgba(255,215,0,0.3)',
                borderRadius: 12,
                overflow: 'hidden',
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <StarFilled style={{ color: '#ffd700', fontSize: 16 }} />
                <Tag color="gold" style={{ margin: 0, fontWeight: 600, fontSize: 11 }}>FEATURED</Tag>
              </div>
              <Title level={3} style={{ color: '#fff', margin: '4px 0 8px' }}>{campaign.title}</Title>
              {campaign.description && (
                <Paragraph style={{ color: 'rgba(255,255,255,0.7)', margin: '0 0 12px', fontSize: isMobile ? 15 : 14 }} ellipsis={{ rows: 2 }}>
                  {campaign.description}
                </Paragraph>
              )}
              <div style={{ display: 'flex', gap: 24, flexWrap: 'wrap', alignItems: 'center' }}>
                {campaign.showEmailCount && (
                  <Statistic
                    value={campaign._count.emails}
                    suffix="emails sent"
                    valueStyle={{ color: token.colorPrimary, fontSize: 18, fontWeight: 700 }}
                  />
                )}
                {campaign.showResponseWall && campaign._count.responses > 0 && (
                  <Statistic
                    value={campaign._count.responses}
                    suffix="responses"
                    valueStyle={{ color: token.colorSuccess, fontSize: 18, fontWeight: 700 }}
                  />
                )}
                {campaign.targetGovernmentLevels.map((l: GovernmentLevel) => (
                  <Tag key={l} color={GOVERNMENT_LEVEL_COLORS[l]}>{GOVERNMENT_LEVEL_LABELS[l]}</Tag>
                ))}
              </div>
            </Card>
          </Link>
          <ShareButtons campaign={campaign} isMobile={isMobile} />
        </div>
      ))}

      <AdBanner ads={campaignListAds} placement="campaigns_list" />

      {/* Campaigns Grid */}
      <Title level={3} style={{ color: 'rgba(255,255,255,0.85)', textAlign: 'center', marginBottom: 8 }}>
        Active Campaigns
      </Title>
      <Paragraph style={{ color: 'rgba(255,255,255,0.55)', textAlign: 'center', marginBottom: 24, fontSize: isMobile ? 15 : 14 }}>
        Join ongoing campaigns to make your voice heard on important issues
      </Paragraph>

      {campaigns.length === 0 ? (
        <Empty
          description={<Text style={{ color: 'rgba(255,255,255,0.45)' }}>No active campaigns</Text>}
          style={{ padding: 60 }}
        />
      ) : nonFeatured.length === 0 ? (
        <Empty
          description={<Text style={{ color: 'rgba(255,255,255,0.45)' }}>Check out the featured campaign above</Text>}
          style={{ padding: 60 }}
        />
      ) : (
        <Row gutter={[20, 20]}>
          {nonFeatured.map((campaign) => (
            <Col xs={24} sm={12} lg={8} key={campaign.id}>
              <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                <Card
                  style={{
                    flex: 1,
                    background: colorBgContainer,
                    border: '1px solid rgba(255,255,255,0.08)',
                    borderRadius: 10,
                    overflow: 'hidden',
                  }}
                  styles={{ body: { padding: 0, display: 'flex', flexDirection: 'column', height: '100%' } }}
                >
                  <Link to={`/campaign/${campaign.slug}`} style={{ display: 'block', flex: 1, padding: 20 }}>
                    {campaign.coverPhoto && (
                      <div
                        style={{
                          height: 140,
                          margin: '-20px -20px 16px -20px',
                          backgroundImage: `url(${campaign.coverPhoto})`,
                          backgroundSize: 'cover',
                          backgroundPosition: 'center',
                        }}
                      />
                    )}
                    <Title level={4} style={{ color: '#fff', margin: '0 0 12px', fontSize: isMobile ? 18 : 17, lineHeight: 1.35 }} ellipsis={{ rows: 2 }}>
                      {campaign.title}
                    </Title>
                    {campaign.description && (
                      <Paragraph
                        style={{ color: 'rgba(255,255,255,0.55)', fontSize: isMobile ? 14 : 13, margin: '0 0 12px', lineHeight: 1.5 }}
                        ellipsis={{ rows: 2 }}
                      >
                        {campaign.description}
                      </Paragraph>
                    )}
                    <div style={{ marginBottom: 8, display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                      {campaign.targetGovernmentLevels.map((l: GovernmentLevel) => (
                        <Tag key={l} color={GOVERNMENT_LEVEL_COLORS[l]} style={{ fontSize: 11 }}>
                          {GOVERNMENT_LEVEL_LABELS[l]}
                        </Tag>
                      ))}
                      {isTrending(campaign) && <Tag color="volcano" style={{ fontSize: 11 }}>Trending</Tag>}
                      {isNew(campaign.createdAt) && <Tag color="cyan" style={{ fontSize: 11 }}>New</Tag>}
                    </div>
                    <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
                      {campaign.showEmailCount && (
                        <span style={{ color: token.colorPrimary, fontSize: isMobile ? 14 : 13 }}>
                          <MailOutlined style={{ marginRight: 4 }} />
                          {campaign._count.emails} emails sent
                        </span>
                      )}
                      {campaign.showResponseWall && (
                        <span style={{ color: token.colorSuccess, fontSize: isMobile ? 14 : 13 }}>
                          <MessageOutlined style={{ marginRight: 4 }} />
                          {campaign._count.responses} responses
                        </span>
                      )}
                    </div>
                  </Link>
                  <div style={{ borderTop: '1px solid rgba(255,255,255,0.06)', padding: '8px 20px' }}>
                    <ShareButtons campaign={campaign} compact isMobile={isMobile} />
                    <Link to={`/campaign/${campaign.slug}`} style={{ display: 'block', marginTop: 4 }}>
                      <Button type="link" style={{ padding: 0, color: token.colorPrimary, fontSize: 13 }}>
                        Learn More & Participate <ArrowRightOutlined />
                      </Button>
                    </Link>
                  </div>
                </Card>
              </div>
            </Col>
          ))}
        </Row>
      )}

      {total > 20 && (
        <div style={{ textAlign: 'center', marginTop: 32 }}>
          <Pagination
            current={page}
            total={total}
            pageSize={20}
            onChange={(p) => { setPage(p); window.scrollTo({ top: 0, behavior: 'smooth' }); }}
            showSizeChanger={false}
          />
        </div>
      )}

      <AuthModal
        open={authModalOpen}
        onCancel={() => setAuthModalOpen(false)}
        onSuccess={() => {
          setAuthModalOpen(false);
          navigate('/campaigns/create');
        }}
        title="Sign in to Create a Campaign"
        subtitle="Sign in or create an account to submit your own campaign"
      />
    </div>
  );
}

// --- Representative Card Component ---

function RepCard({
  rep,
  isMobile,
  token: tkn,
  colorBgContainer,
  campaigns,
  onOpenDrawer,
  campaignSelectorContent,
}: {
  rep: Representative;
  isMobile: boolean;
  token: ReturnType<typeof theme.useToken>['token'];
  colorBgContainer: string;
  campaigns: Campaign[];
  onOpenDrawer: () => void;
  campaignSelectorContent: React.ReactNode;
}) {
  const firstPhone = rep.offices?.find(o => o.tel);

  return (
    <Card
      style={{
        background: colorBgContainer,
        border: '1px solid rgba(255,255,255,0.08)',
        borderRadius: 12,
      }}
      styles={{ body: { padding: isMobile ? 16 : 20 } }}
    >
      {/* Header: Avatar + Name + Title */}
      <div style={{
        display: 'flex',
        gap: isMobile ? 12 : 16,
        flexDirection: isMobile ? 'column' : 'row',
        alignItems: isMobile ? 'center' : 'flex-start',
      }}>
        <Avatar
          src={rep.photoUrl}
          icon={!rep.photoUrl ? <UserOutlined /> : undefined}
          size={isMobile ? 80 : 72}
          style={{ flexShrink: 0, border: '2px solid rgba(255,255,255,0.1)' }}
        />
        <div style={{ flex: 1, width: '100%' }}>
          {/* Name */}
          <Text strong style={{
            color: tkn.colorPrimary,
            fontSize: isMobile ? 20 : 18,
            display: 'block',
            textAlign: isMobile ? 'center' : 'left',
            lineHeight: 1.3,
          }}>
            {rep.name || 'Unknown'}
          </Text>

          {/* Role subtitle */}
          {rep.electedOffice && (
            <Text style={{
              color: 'rgba(255,255,255,0.6)',
              fontSize: isMobile ? 15 : 14,
              display: 'block',
              textAlign: isMobile ? 'center' : 'left',
              marginTop: 2,
            }}>
              {rep.electedOffice}
            </Text>
          )}

          {/* Info grid */}
          <div style={{
            marginTop: 12,
            display: 'grid',
            gridTemplateColumns: isMobile ? '1fr' : 'auto 1fr',
            gap: isMobile ? '6px 0' : '4px 12px',
            fontSize: isMobile ? 15 : 14,
            lineHeight: 1.6,
          }}>
            {rep.districtName && (
              <>
                <Text style={{ color: 'rgba(255,255,255,0.45)', whiteSpace: 'nowrap' }}>
                  <EnvironmentOutlined style={{ marginRight: 6 }} />District
                </Text>
                <Text style={{ color: 'rgba(255,255,255,0.85)' }}>{rep.districtName}</Text>
              </>
            )}
            {rep.partyName && (
              <>
                <Text style={{ color: 'rgba(255,255,255,0.45)', whiteSpace: 'nowrap' }}>
                  <BankOutlined style={{ marginRight: 6 }} />Party
                </Text>
                <Text style={{ color: 'rgba(255,255,255,0.85)' }}>{rep.partyName}</Text>
              </>
            )}
            {rep.email && (
              <>
                <Text style={{ color: 'rgba(255,255,255,0.45)', whiteSpace: 'nowrap' }}>
                  <MailOutlined style={{ marginRight: 6 }} />Email
                </Text>
                <Text style={{ color: 'rgba(255,255,255,0.85)', wordBreak: 'break-all' }}>{rep.email}</Text>
              </>
            )}
            {firstPhone && (
              <>
                <Text style={{ color: 'rgba(255,255,255,0.45)', whiteSpace: 'nowrap' }}>
                  <PhoneOutlined style={{ marginRight: 6 }} />Phone
                </Text>
                <Text style={{ color: 'rgba(255,255,255,0.85)' }}>
                  {firstPhone.tel}{firstPhone.type ? ` (${firstPhone.type})` : ''}
                </Text>
              </>
            )}
            {rep.offices?.filter(o => o.tel && o !== firstPhone).map((office, oi) => (
              <div key={oi} style={{ gridColumn: isMobile ? '1' : '1 / -1', paddingLeft: isMobile ? 0 : 24 }}>
                <Text style={{ color: 'rgba(255,255,255,0.65)', fontSize: isMobile ? 14 : 13 }}>
                  <PhoneOutlined style={{ marginRight: 6, opacity: 0.5 }} />
                  {office.tel}{office.type ? ` (${office.type})` : ''}
                </Text>
              </div>
            ))}
          </div>

          {/* Office addresses */}
          {rep.offices && rep.offices.some(o => o.postal) && (
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 10 }}>
              {rep.offices.filter(o => o.postal).slice(0, 2).map((office, oi) => (
                <Tag key={oi} color="processing" style={{ fontSize: isMobile ? 12 : 11, lineHeight: '20px' }}>
                  {office.type || 'Office'}: {office.postal}
                </Tag>
              ))}
              {rep.offices.filter(o => o.postal).length > 2 && (
                <Tag style={{ fontSize: 11, lineHeight: '20px' }}>
                  +{rep.offices.filter(o => o.postal).length - 2} more
                </Tag>
              )}
            </div>
          )}

          {/* Action Buttons */}
          <div style={{
            display: 'flex',
            gap: isMobile ? 10 : 8,
            flexWrap: 'wrap',
            marginTop: 16,
            flexDirection: isMobile ? 'column' : 'row',
          }}>
            {rep.email && (
              isMobile ? (
                <Button
                  type="primary"
                  size="large"
                  icon={<SendOutlined />}
                  block
                  onClick={onOpenDrawer}
                >
                  Send via Campaign
                </Button>
              ) : (
                <Popover
                  trigger="click"
                  placement="bottomLeft"
                  title={campaigns.length > 0 ? 'Choose a Campaign' : 'Take Action'}
                  content={<div style={{ maxWidth: 340, maxHeight: 400, overflowY: 'auto' }}>{campaignSelectorContent}</div>}
                >
                  <Button type="primary" icon={<SendOutlined />}>
                    Send via Campaign
                  </Button>
                </Popover>
              )
            )}
            {rep.email && (
              <Tooltip title="Open your default email app to compose a message">
                <Button
                  size={isMobile ? 'large' : 'middle'}
                  icon={<MailOutlined />}
                  onClick={() => window.open(`mailto:${rep.email}`, '_blank')}
                  block={isMobile}
                >
                  Email Directly
                </Button>
              </Tooltip>
            )}
            <div style={{ display: 'flex', gap: isMobile ? 10 : 8, width: isMobile ? '100%' : 'auto' }}>
              {rep.offices?.some(o => o.tel) && (
                <Button
                  size={isMobile ? 'large' : 'middle'}
                  icon={<PhoneOutlined />}
                  style={{ background: '#16a34a', border: 'none', color: '#fff', flex: isMobile ? 1 : undefined }}
                  onClick={() => {
                    const phone = rep.offices?.find(o => o.tel)?.tel;
                    if (phone) window.location.href = `tel:${phone.replace(/\s/g, '')}`;
                  }}
                >
                  Call
                </Button>
              )}
              {rep.url && (
                <Button
                  size={isMobile ? 'large' : 'middle'}
                  icon={<GlobalOutlined />}
                  onClick={() => window.open(rep.url!, '_blank', 'noopener,noreferrer')}
                  style={{ flex: isMobile ? 1 : undefined }}
                >
                  Profile
                </Button>
              )}
            </div>
          </div>
        </div>
      </div>
    </Card>
  );
}

// --- Share Buttons Component ---

function ShareButtons({ campaign, compact, isMobile }: { campaign: Campaign; compact?: boolean; isMobile?: boolean }) {
  const url = `${window.location.origin}/campaign/${campaign.slug}`;
  const text = `${campaign.title} - Take action now!`;

  // On mobile, use native share API if available
  if (isMobile && typeof navigator !== 'undefined' && navigator.share) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: compact ? 0 : 8 }}>
        <Button
          size="small"
          icon={<CopyOutlined />}
          onClick={async (e) => {
            e.stopPropagation();
            e.preventDefault();
            try {
              await navigator.share({ title: campaign.title, url });
            } catch {
              // User cancelled
            }
          }}
        >
          Share
        </Button>
      </div>
    );
  }

  const shareLinks = [
    {
      label: 'Share on X',
      shortLabel: 'X',
      icon: <span style={{ fontWeight: 700, fontSize: compact ? 12 : 14 }}>&#x1D54F;</span>,
      href: `https://twitter.com/intent/tweet?url=${encodeURIComponent(url)}&text=${encodeURIComponent(text)}`,
    },
    {
      label: 'Share on Facebook',
      shortLabel: 'Facebook',
      icon: <span style={{ fontWeight: 700, fontSize: compact ? 12 : 14 }}>f</span>,
      href: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`,
    },
    {
      label: 'Share on LinkedIn',
      shortLabel: 'LinkedIn',
      icon: <span style={{ fontWeight: 700, fontSize: compact ? 11 : 13 }}>in</span>,
      href: `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`,
    },
    {
      label: 'Share on Reddit',
      shortLabel: 'Reddit',
      icon: <span style={{ fontWeight: 700, fontSize: compact ? 12 : 14 }}>r/</span>,
      href: `https://reddit.com/submit?url=${encodeURIComponent(url)}&title=${encodeURIComponent(campaign.title)}`,
    },
    {
      label: 'Share via Email',
      shortLabel: 'Email',
      icon: <MailOutlined style={{ fontSize: compact ? 12 : 14 }} />,
      href: `mailto:?subject=${encodeURIComponent(campaign.title)}&body=${encodeURIComponent(`Check out this campaign: ${url}`)}`,
    },
  ];

  const handleCopy = () => {
    navigator.clipboard.writeText(url);
    message.success('Link copied!');
  };

  const size = compact ? 30 : 34;
  const btnStyle: React.CSSProperties = {
    width: size,
    height: size,
    minWidth: size,
    padding: 0,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: '50%',
    border: '1px solid rgba(255,255,255,0.15)',
    background: 'transparent',
    color: 'rgba(255,255,255,0.6)',
    cursor: 'pointer',
    transition: 'all 0.2s',
  };

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: compact ? 6 : 8, marginTop: compact ? 0 : 8, flexWrap: 'wrap' }}>
      <Text style={{ color: 'rgba(255,255,255,0.45)', fontSize: compact ? 12 : 13 }}>Share:</Text>
      {shareLinks.map((link) => (
        <Tooltip key={link.shortLabel} title={link.shortLabel}>
          <a
            href={link.href}
            target="_blank"
            rel="noopener noreferrer"
            style={btnStyle}
            onClick={(e) => e.stopPropagation()}
            aria-label={link.label}
          >
            {link.icon}
          </a>
        </Tooltip>
      ))}
      <Tooltip title="Copy Link">
        <button
          onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleCopy(); }}
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault();
              e.stopPropagation();
              handleCopy();
            }
          }}
          style={btnStyle}
          aria-label="Copy link to campaign"
        >
          <CopyOutlined style={{ fontSize: compact ? 12 : 14 }} />
        </button>
      </Tooltip>
    </div>
  );
}
