import React, { useState, useEffect, useCallback, useRef, memo } from 'react';
import { useAuth } from '../../../auth/AuthProvider';
import { useWizardConfig } from '../../../context/WizardConfigContext';
import { getTemplates } from '../../../services/initiativeApi';
import { getAudienceRecommendation } from '../../../services/wizardApi';
import { getChannelForecast } from '../../../services/forecastApi';
import HelpIcon from '../../../components/HelpIcon';

const fmt = (n) => n != null ? Number(n).toLocaleString(undefined, { maximumFractionDigits: 0 }) : '—';
const fmtDec = (n, d = 2) => n != null ? Number(n).toLocaleString(undefined, { minimumFractionDigits: d, maximumFractionDigits: d }) : '—';

const channelIcons = {
  google_ads: (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="10" stroke="#4285F4" strokeWidth="2"/>
      <text x="12" y="16" textAnchor="middle" fontSize="12" fontWeight="bold" fill="#4285F4">G</text>
    </svg>
  ),
  meta: (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="10" stroke="#0668E1" strokeWidth="2"/>
      <text x="12" y="16" textAnchor="middle" fontSize="12" fontWeight="bold" fill="#0668E1">M</text>
    </svg>
  ),
  tiktok: (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="10" stroke="#000000" strokeWidth="2"/>
      <text x="12" y="16" textAnchor="middle" fontSize="12" fontWeight="bold" fill="#000000">T</text>
    </svg>
  ),
};

const ChannelAllocationStep = memo(function ChannelAllocationStep({
  data, onChange, objectiveData, audienceData, budgetData
}) {
  const { sessionToken } = useAuth();
  const { getChannelLabel, getChannelColor, channels, allocationRules, loading } = useWizardConfig();

  // ── Template state (fallback) ──
  const [templates, setTemplates] = useState([]);
  const [loadingTemplates, setLoadingTemplates] = useState(false);

  // ── Forecast state ──
  const [forecast, setForecast] = useState(null);
  const [forecastLoading, setForecastLoading] = useState(false);
  const [forecastError, setForecastError] = useState(null);
  const forecastTimer = useRef(null);

  const state = {
    selectedChannels: [],
    allocations: {},
    allocationStrategy: 'manual',
    ...data
  };

  const selectedChannels = state.selectedChannels || [];
  const isMultiChannel = selectedChannels.length > 1;

  // Budget comes from step 3 now
  const totalBudget = parseFloat(budgetData?.totalBudget) || 0;
  const budgetPeriod = budgetData?.budgetPeriod || 'monthly';
  const monthlyBudget = budgetPeriod === 'daily' ? totalBudget * 30 : totalBudget;

  const update = useCallback((patch) => {
    onChange({ ...state, ...patch });
  }, [state, onChange]);

  // ── Channel toggle ──
  const toggleChannel = (channelType) => {
    const current = state.selectedChannels;
    const updated = current.includes(channelType)
      ? current.filter(c => c !== channelType)
      : [...current, channelType];
    update({ selectedChannels: updated });
  };

  const isSelected = (channelType) => state.selectedChannels.includes(channelType);
  const objective = objectiveData?.objective;
  const selectedCount = state.selectedChannels.length;

  // ── Initialize allocations for selected channels ──
  useEffect(() => {
    const current = state.allocations || {};
    const needsInit = selectedChannels.some(ch => !(ch in current))
      || selectedChannels.length !== Object.keys(current).length;

    if (needsInit && selectedChannels.length > 0) {
      const evenSplit = Math.floor(100 / selectedChannels.length);
      const remainder = 100 - (evenSplit * selectedChannels.length);
      const updated = {};
      selectedChannels.forEach((ch, idx) => {
        updated[ch] = current[ch] || (evenSplit + (idx === 0 ? remainder : 0));
      });
      update({ allocations: updated });
    }
  }, [selectedChannels.join(',')]);

  // ── Channel strength descriptions ──
  const getChannelStrength = (channelType) => {
    const strengths = {
      google_ads: {
        awareness: 'Strong reach via Display & YouTube',
        traffic: 'High-intent search traffic',
        leads: 'Search captures active prospects',
        conversions: 'Intent-driven conversion engine',
        sales: 'Shopping & search drive purchases',
      },
      meta: {
        awareness: 'Massive reach on Facebook & Instagram',
        traffic: 'Visual storytelling drives clicks',
        leads: 'Lead forms built into the platform',
        conversions: 'Advanced pixel tracking & lookalikes',
        sales: 'Shop integration & dynamic product ads',
      },
      tiktok: {
        awareness: 'Viral potential with younger audiences',
        traffic: 'Engaging video drives curiosity clicks',
        leads: 'Growing lead gen capabilities',
        conversions: 'Strong for impulse & discovery',
        sales: 'TikTok Shop integration',
      },
    };
    return strengths[channelType]?.[objective] || null;
  };

  const supportsObjective = (channel) => {
    if (!objective || !channel.supportedObjectives) return true;
    return channel.supportedObjectives.includes(objective);
  };

  const isRecommended = (channelType) => {
    const recs = {
      awareness: ['meta', 'tiktok', 'google_ads'],
      traffic: ['google_ads', 'meta'],
      leads: ['google_ads', 'meta'],
      conversions: ['google_ads', 'meta'],
      sales: ['google_ads', 'meta'],
    };
    return objective ? (recs[objective] || []).includes(channelType) : false;
  };

  // Budget-aware channel filtering
  const isAffordable = (channel) => {
    if (monthlyBudget <= 0) return true; // Don't filter if no budget set
    return monthlyBudget >= (channel.minMonthlyBudget || 0);
  };

  // Audience context
  const audienceSummary = [];
  if (audienceData?.marketScope && audienceData.marketScope !== 'national') {
    audienceSummary.push(audienceData.marketScope + ' market');
  }
  if (audienceData?.ageSkew) {
    audienceSummary.push(audienceData.ageSkew === 'young' ? 'younger audience' : 'mature audience');
  }

  // ── Load template recommendations (fallback) ──
  useEffect(() => {
    if (!isMultiChannel) return;
    async function loadTemplates() {
      setLoadingTemplates(true);
      const ageSkew = audienceData?.ageSkew || null;
      const marketScope = audienceData?.marketScope || null;

      if (ageSkew || marketScope) {
        const recRes = await getAudienceRecommendation(
          objectiveData?.businessCategory, objectiveData?.objective,
          ageSkew, marketScope, sessionToken
        );
        if (recRes.ok && recRes.data?.channels) {
          const chs = recRes.data.channels || recRes.data.data?.channels || [];
          setTemplates(chs.map(ch => ({
            channelType: ch.channelType,
            allocationPct: ch.recommendedPct,
            rationale: ch.baseRationale,
          })));
          setLoadingTemplates(false);
          return;
        }
      }
      const res = await getTemplates(sessionToken, objectiveData?.businessCategory, objectiveData?.objective);
      if (res.ok) {
        const list = res.data?.data || res.data?.templates || [];
        setTemplates(Array.isArray(list) ? list : []);
      }
      setLoadingTemplates(false);
    }
    loadTemplates();
  }, [sessionToken, objectiveData?.businessCategory, objectiveData?.objective, isMultiChannel, audienceData?.ageSkew, audienceData?.marketScope]);

  // ════════════════════════════════════════════════
  // Forecast: debounced call when budget/channels change
  // ════════════════════════════════════════════════

  const fetchForecast = useCallback(async (budget) => {
    if (!budget || budget <= 0 || selectedChannels.length === 0) {
      setForecast(null);
      return;
    }

    const analysis = objectiveData?.analysis;
    const keywords = [];
    if (analysis?.keywords) keywords.push(...analysis.keywords);
    if (analysis?.suggestedKeywords) keywords.push(...analysis.suggestedKeywords);
    if (keywords.length === 0) {
      if (analysis?.title) keywords.push(analysis.title);
      if (objectiveData?.businessCategory) keywords.push(objectiveData.businessCategory);
      if (analysis?.metaDescription) {
        const words = analysis.metaDescription.split(/\s+/).slice(0, 6).join(' ');
        if (words) keywords.push(words);
      }
    }

    if (keywords.length === 0) {
      setForecastError('No keywords available — analyze your URL in Step 1');
      return;
    }

    const geoTargeting = {};
    if (audienceData?.locations?.length > 0) {
      geoTargeting.zipCodes = audienceData.locations
        .filter(l => l.type === 'zip' || l.zipCode)
        .map(l => l.zipCode || l.value);
      geoTargeting.geoTargetIds = audienceData.locations
        .filter(l => l.geoTargetId)
        .map(l => l.geoTargetId);
    }

    const audience = {
      ageMin: audienceData?.demographics?.ageMin,
      ageMax: audienceData?.demographics?.ageMax,
    };

    setForecastLoading(true);
    setForecastError(null);

    const res = await getChannelForecast({
      objective: objectiveData?.objective || 'traffic',
      businessCategory: objectiveData?.businessCategory,
      keywords,
      geoTargeting,
      audience,
      monthlyBudget: budget,
      channels: selectedChannels,
    }, sessionToken);

    setForecastLoading(false);

    if (res.ok && res.data?.channels) {
      setForecast(res.data);

      if (isMultiChannel && res.data.channels.length > 0) {
        const newAllocations = {};
        res.data.channels.forEach(ch => {
          if (selectedChannels.includes(ch.provider)) {
            newAllocations[ch.provider] = ch.allocationPercent;
          }
        });
        if (state.allocationStrategy !== 'manual-adjusted') {
          update({
            allocations: newAllocations,
            allocationStrategy: 'forecast'
          });
        }
      }
    } else {
      setForecastError(res.error || 'Could not load estimates');
    }
  }, [selectedChannels.join(','), objectiveData?.objective, objectiveData?.businessCategory, objectiveData?.analysis, audienceData, sessionToken]);

  // Debounce: re-forecast when budget or channels change
  useEffect(() => {
    if (forecastTimer.current) clearTimeout(forecastTimer.current);
    if (monthlyBudget > 0 && selectedChannels.length > 0) {
      forecastTimer.current = setTimeout(() => fetchForecast(monthlyBudget), 800);
    } else {
      setForecast(null);
    }
    return () => { if (forecastTimer.current) clearTimeout(forecastTimer.current); };
  }, [monthlyBudget, selectedChannels.join(','), fetchForecast]);

  // ── Derived allocation values ──
  const totalPct = Object.values(state.allocations).reduce((sum, v) => sum + (v || 0), 0);
  const isBalanced = Math.abs(totalPct - 100) < 0.01;

  const handleAllocationChange = (channel, value) => {
    const pct = Math.max(0, Math.min(100, parseInt(value) || 0));
    update({
      allocations: { ...state.allocations, [channel]: pct },
      allocationStrategy: 'manual-adjusted'
    });
  };

  const applyForecastAllocations = () => {
    if (!forecast?.channels) return;
    const newAllocations = {};
    forecast.channels.forEach(ch => {
      if (selectedChannels.includes(ch.provider)) {
        newAllocations[ch.provider] = ch.allocationPercent;
      }
    });
    update({ allocations: newAllocations, allocationStrategy: 'forecast' });
  };

  const applyTemplate = (template) => {
    const newAllocations = {};
    selectedChannels.forEach(ch => {
      const match = template.find(t => (t.channelType || t.atlChannelType) === ch);
      newAllocations[ch] = match ? parseFloat(match.allocationPct || match.atlAllocationPct || 0) : 0;
    });
    update({ allocations: newAllocations, allocationStrategy: 'template' });
  };

  const getChannelEstimate = (channelType) => {
    if (!forecast?.channels) return null;
    const fc = forecast.channels.find(c => c.provider === channelType);
    if (!fc) return null;
    const forecastPct = fc.allocationPercent || 1;
    const currentPct = state.allocations[channelType] || forecastPct;
    const scale = currentPct / forecastPct;
    return {
      ...fc,
      scaled: {
        impressions: Math.round((fc.estimates?.impressions || 0) * scale),
        reach: fc.estimates?.reach ? Math.round(fc.estimates.reach * scale) : null,
        clicks: Math.round((fc.estimates?.clicks || 0) * scale),
        conversions: Math.round(((fc.estimates?.conversions || 0) * scale) * 10) / 10,
      },
      allocatedBudget: Math.round(monthlyBudget * currentPct / 100),
    };
  };

  // ════════════════════════════════════════════════
  // Render
  // ════════════════════════════════════════════════

  return (
    <div className="wizard-step-content">
      <div className="step-intro">
        <div className="step-intro-header">
          <h2>Choose your channels{isMultiChannel ? ' & allocation' : ''}</h2>
          <HelpIcon helpKey="client.wizard.channels" label="About this step" />
        </div>
        <p>
          {monthlyBudget > 0
            ? `With your $${monthlyBudget.toLocaleString()}/mo budget, select the channels where you want to advertise.`
            : 'Select one or more advertising channels.'}
          {selectedCount > 1 ? ` We'll show estimated performance and help you split the budget.` : ''}
          {objective ? ` All optimized for your ${objective} objective.` : ''}
        </p>
      </div>

      {/* Budget & Audience Context Bar */}
      <div className="channel-context-bar">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
        </svg>
        <span>
          {monthlyBudget > 0 && <><strong>${monthlyBudget.toLocaleString()}/mo</strong> budget</>}
          {objective && <>{monthlyBudget > 0 ? ' · ' : ''}Optimized for <strong>{objective}</strong></>}
          {audienceSummary.length > 0 && <> · {audienceSummary.join(' and ')}</>}
          {objectiveData?.businessCategory && <> · <strong>{objectiveData.businessCategory}</strong></>}
        </span>
      </div>

      {/* ── Channel Selection Grid ── */}
      {loading ? (
        <div className="loading-placeholder padded">
          {[1, 2, 3].map(i => (
            <div key={i} className="skeleton skeleton-row" style={{ height: 120, marginBottom: 16 }} />
          ))}
        </div>
      ) : (
        <>
          <div className="channel-grid">
            {channels.map(channel => {
              const selected = isSelected(channel.channelType);
              const supported = supportsObjective(channel);
              const affordable = isAffordable(channel);
              const recommended = isRecommended(channel.channelType);
              const strength = getChannelStrength(channel.channelType);
              const borderColor = selected ? (channel.color || '#4F46E5') : 'transparent';
              const disabled = !supported || !affordable;

              return (
                <button
                  key={channel.channelType}
                  className={`channel-card ${selected ? 'selected' : ''} ${disabled ? 'unsupported' : ''}`}
                  style={{ '--channel-color': channel.color || '#4F46E5', borderColor }}
                  onClick={() => !disabled && toggleChannel(channel.channelType)}
                  disabled={disabled}
                >
                  <div className="channel-card-header">
                    <div className="channel-icon">
                      {channelIcons[channel.channelType] || (
                        <div className="channel-icon-fallback" style={{ background: channel.color || '#4F46E5' }}>
                          {channel.displayName?.charAt(0)}
                        </div>
                      )}
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      {recommended && supported && affordable && (
                        <span className="channel-rec-badge">
                          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M20 6L9 17l-5-5" /></svg>
                          Recommended
                        </span>
                      )}
                      <div className="channel-card-check">
                        {selected ? (
                          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                            <path d="M20 6L9 17l-5-5" />
                          </svg>
                        ) : (
                          <div className="check-empty" />
                        )}
                      </div>
                    </div>
                  </div>

                  <div className="channel-card-body">
                    <div className="channel-name">
                      {channel.displayName}
                      {channel.isStub && <span className="stub-badge">Preview</span>}
                    </div>
                    <div className="channel-desc">{channel.description}</div>
                    {strength && (
                      <div className="channel-strength">
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" /></svg>
                        {strength}
                      </div>
                    )}
                  </div>

                  <div className="channel-card-footer">
                    <span className="channel-min-budget">
                      Min ${channel.minMonthlyBudget || 0}/mo
                    </span>
                    {!supported && (
                      <span className="channel-unsupported-label">
                        Not available for {objective}
                      </span>
                    )}
                    {supported && !affordable && (
                      <span className="channel-unsupported-label">
                        Requires ${channel.minMonthlyBudget}/mo minimum
                      </span>
                    )}
                  </div>
                </button>
              );
            })}
          </div>

          {/* Selection summary */}
          {selectedCount > 0 && (
            <div className="channel-summary">
              <div className="channel-summary-chips">
                {state.selectedChannels.map(ct => {
                  const ch = channels.find(c => c.channelType === ct);
                  return (
                    <span key={ct} className="channel-chip" style={{ borderColor: ch?.color || '#4F46E5' }}>
                      {ch?.displayName || ct}
                      <button onClick={() => toggleChannel(ct)} className="chip-remove">×</button>
                    </span>
                  );
                })}
              </div>
              <div className="channel-summary-info">
                {selectedCount === 1
                  ? 'Single-channel campaign'
                  : `Multi-channel campaign across ${selectedCount} platforms`}
                {selectedCount > 1 && allocationRules && (
                  <span className="channel-summary-note">
                    {' '}· Minimum total budget: ${allocationRules.minMultiChannelMonthlyBudget}/mo
                  </span>
                )}
              </div>
            </div>
          )}

          {selectedCount === 0 && (
            <div className="channel-empty-hint">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span>Select at least one channel to continue</span>
            </div>
          )}
        </>
      )}

      {/* ════════════════════════════════════════════════ */}
      {/* Forecast + Allocation (appears after channels selected + budget set) */}
      {/* ════════════════════════════════════════════════ */}

      {selectedCount > 0 && monthlyBudget > 0 && (
        <div className="forecast-section">

          {/* Loading indicator */}
          {forecastLoading && (
            <div className="forecast-loading">
              <span className="btn-spinner" />
              <span>Getting performance estimates from ad platforms…</span>
            </div>
          )}

          {/* Forecast card */}
          {forecast && !forecastLoading && (
            <div className="forecast-card">
              <div className="forecast-card-header">
                <div className="forecast-title">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                  </svg>
                  <span>Estimated Performance at ${monthlyBudget.toLocaleString()}/mo</span>
                </div>
                {forecast.recommendation && (
                  <span className="forecast-objective-tag">
                    Optimized for {objectiveData?.objective || 'traffic'}
                  </span>
                )}
              </div>

              {/* Side-by-side channel estimates */}
              <div className="forecast-channels">
                {selectedChannels.map(ch => {
                  const est = getChannelEstimate(ch);
                  const color = getChannelColor(ch);
                  const label = getChannelLabel(ch);
                  const pct = state.allocations[ch] || 0;

                  if (!est || est.dataSource === 'template') {
                    return (
                      <div key={ch} className="forecast-channel forecast-channel-template">
                        <div className="forecast-ch-header">
                          <span className="forecast-ch-dot" style={{ background: color }} />
                          <span className="forecast-ch-name">{label} ({pct}%)</span>
                          <span className="forecast-ch-budget">${Math.round(monthlyBudget * pct / 100).toLocaleString()}/mo</span>
                        </div>
                        <div className="forecast-ch-template-note">
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                            <path d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                          </svg>
                          <span>Estimates not yet available. Allocation based on category benchmarks.</span>
                        </div>
                      </div>
                    );
                  }

                  return (
                    <div key={ch} className="forecast-channel">
                      <div className="forecast-ch-header">
                        <span className="forecast-ch-dot" style={{ background: color }} />
                        <span className="forecast-ch-name">{label} ({pct}%)</span>
                        <span className="forecast-ch-budget">${est.allocatedBudget.toLocaleString()}/mo</span>
                      </div>
                      <div className="forecast-ch-metrics">
                        {est.scaled.reach && (
                          <div className="forecast-metric">
                            <span className="forecast-metric-value">~{fmt(est.scaled.reach)}</span>
                            <span className="forecast-metric-label">reach</span>
                          </div>
                        )}
                        <div className="forecast-metric">
                          <span className="forecast-metric-value">~{fmt(est.scaled.impressions)}</span>
                          <span className="forecast-metric-label">impressions</span>
                        </div>
                        <div className="forecast-metric">
                          <span className="forecast-metric-value">~{fmt(est.scaled.clicks)}</span>
                          <span className="forecast-metric-label">clicks</span>
                        </div>
                        <div className="forecast-metric">
                          <span className="forecast-metric-value">~{fmt(est.scaled.conversions)}</span>
                          <span className="forecast-metric-label">est. conv.</span>
                        </div>
                      </div>
                      <div className="forecast-ch-detail">
                        <span>${fmtDec(est.estimates?.avgCpc)} avg CPC</span>
                        <span>${fmtDec(est.estimates?.avgCpm)} avg CPM</span>
                        {est.estimates?.estimatedCpa && (
                          <span>${fmtDec(est.estimates.estimatedCpa)} est. CPA</span>
                        )}
                      </div>
                      <div className="forecast-ch-strength">
                        <span className="forecast-strength-dot" style={{ background: color }} />
                        {est.strengthLabel}
                      </div>
                      {est.confidence !== 'medium' && est.confidence !== 'high' && (
                        <div className="forecast-ch-confidence">
                          {est.dataSource === 'emulated' ? '○ Estimated' : `○ ${est.confidence}`}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              {/* Recommendation highlights */}
              {forecast.recommendation?.highlights?.length > 0 && (
                <div className="forecast-highlights">
                  {forecast.recommendation.highlights.map((h, i) => (
                    <span key={i} className="forecast-highlight">{h}</span>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Forecast error — fall back to template */}
          {forecastError && !forecastLoading && (
            <div className="forecast-error">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span>{forecastError}</span>
            </div>
          )}
        </div>
      )}

      {/* ── Multi-Channel Allocation Sliders ── */}
      {isMultiChannel && selectedCount > 0 && (
        <div className="allocation-section">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <label style={{ margin: 0, fontWeight: 600 }}>Channel Allocation</label>
            <div style={{ display: 'flex', gap: 8 }}>
              {/* Template fallback button (if no forecast) */}
              {!forecast && templates.length > 0 && (
                <button className="btn btn-sm btn-outline" onClick={() => applyTemplate(templates)}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                  </svg>
                  Apply Template
                </button>
              )}
              {state.allocationStrategy === 'manual-adjusted' && forecast && (
                <button className="btn btn-sm btn-outline forecast-reset-btn" onClick={applyForecastAllocations}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                  Reset to recommended
                </button>
              )}
            </div>
          </div>

          <div className="allocation-sliders">
            {selectedChannels.map(ch => {
              const pct = state.allocations[ch] || 0;
              const amount = (monthlyBudget * pct / 100);
              const color = getChannelColor(ch);

              return (
                <div key={ch} className="allocation-row">
                  <div className="allocation-label">
                    <span className="alloc-dot" style={{ background: color }} />
                    <span className="alloc-name">{getChannelLabel(ch)}</span>
                  </div>
                  <div className="allocation-controls">
                    <input
                      type="range"
                      min="0"
                      max="100"
                      value={pct}
                      onChange={e => handleAllocationChange(ch, e.target.value)}
                      className="alloc-slider"
                      style={{ '--slider-color': color }}
                    />
                    <div className="alloc-values">
                      <input
                        type="number"
                        className="alloc-pct-input"
                        value={pct}
                        min="0"
                        max="100"
                        onChange={e => handleAllocationChange(ch, e.target.value)}
                      />
                      <span className="alloc-pct-sign">%</span>
                      <span className="alloc-amount">
                        ${amount.toFixed(0)}/{budgetPeriod === 'daily' ? 'day' : 'mo'}
                      </span>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>

          {/* Balance indicator */}
          <div className={`allocation-balance ${isBalanced ? 'balanced' : 'unbalanced'}`}>
            {isBalanced ? (
              <><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20 6L9 17l-5-5" /></svg> Allocations total 100%</>
            ) : (
              <><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg> Allocations total {totalPct}% — must equal 100%</>
            )}
          </div>

          {/* Visual bar */}
          <div className="allocation-bar">
            {selectedChannels.map(ch => {
              const pct = state.allocations[ch] || 0;
              return (
                <div
                  key={ch}
                  className="alloc-bar-segment"
                  style={{ width: `${pct}%`, background: getChannelColor(ch) }}
                  title={`${getChannelLabel(ch)}: ${pct}%`}
                />
              );
            })}
          </div>
        </div>
      )}

      {/* Single channel — show forecast if available */}
      {!isMultiChannel && selectedCount === 1 && monthlyBudget > 0 && forecast && !forecastLoading && (
        <div className="forecast-section">
          <div className="forecast-card forecast-card-single">
            <div className="forecast-card-header">
              <div className="forecast-title">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                </svg>
                <span>Estimated Performance</span>
              </div>
            </div>
            <div className="forecast-channels">
              {forecast.channels.filter(c => c.dataSource !== 'template').map(ch => (
                <div key={ch.provider} className="forecast-channel">
                  <div className="forecast-ch-metrics">
                    <div className="forecast-metric">
                      <span className="forecast-metric-value">~{fmt(ch.estimates?.impressions)}</span>
                      <span className="forecast-metric-label">impressions</span>
                    </div>
                    <div className="forecast-metric">
                      <span className="forecast-metric-value">~{fmt(ch.estimates?.clicks)}</span>
                      <span className="forecast-metric-label">clicks</span>
                    </div>
                    <div className="forecast-metric">
                      <span className="forecast-metric-value">~{fmt(ch.estimates?.conversions)}</span>
                      <span className="forecast-metric-label">est. conv.</span>
                    </div>
                  </div>
                  <div className="forecast-ch-detail">
                    <span>${fmtDec(ch.estimates?.avgCpc)} avg CPC</span>
                    <span>${fmtDec(ch.estimates?.avgCpm)} avg CPM</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
});

export default ChannelAllocationStep;
