import * as icon from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useState, useMemo } from 'react';
import CardBox from '../components/CardBox';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { getPageTitle } from '../config';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { fetch as fetchMetrics } from '../stores/metrics_snapshots/metrics_snapshotsSlice';
import { fetch as fetchAlerts } from '../stores/alerts/alertsSlice';
import { aiResponse } from '../stores/openAiSlice';
import BaseIcon from '../components/BaseIcon';
import BaseButton from '../components/BaseButton';
import { useTranslation } from 'next-i18next';
import ChartLineSample from '../components/ChartLineSample';
import axios from 'axios';

const AdvisorPage = () => {
  const dispatch = useAppDispatch();
  const { t } = useTranslation('common');
  
  const { metrics_snapshots } = useAppSelector((state) => state.metrics_snapshots);
  const { alerts } = useAppSelector((state) => state.alerts);
  const { aiResponse: chatResponse, isAskingResponse } = useAppSelector((state) => state.openAi);

  const [chatInput, setChatInput] = useState('');
  const [messages, setMessages] = useState<Array<{ role: string; content: string }>>([
    { role: 'assistant', content: 'Hello! I am your AI Virtual CFO & Investment Banker. I have integrated 2026 market intelligence, funding opportunities, and capitalization trends into your hub. How can I help you optimize your stewardship, risk, or capital strategy today?' }
  ]);
  const [activeTab, setActiveTab] = useState<'company' | 'competitors' | 'intelligence'>('company');
  const [intelligence, setIntelligence] = useState<any>(null);
  const [modeling, setModeling] = useState<any>(null);
  const [opportunities, setOpportunities] = useState<any>(null);
  const [stewardship, setStewardship] = useState<any>(null);
  const [risk, setRisk] = useState<any>(null);
  const [capital, setCapital] = useState<any>(null);
  const [leadership, setLeadership] = useState<any>(null);
  const [esg, setEsg] = useState<any>(null);

  const [loadingIntelligence, setLoadingIntelligence] = useState(false);
  const [loadingModeling, setLoadingModeling] = useState(false);
  const [loadingOpportunities, setLoadingOpportunities] = useState(false);
  const [loadingStewardship, setLoadingStewardship] = useState(false);
  const [loadingRisk, setLoadingRisk] = useState(false);
  const [loadingCapital, setLoadingCapital] = useState(false);
  const [loadingLeadership, setLoadingLeadership] = useState(false);
  const [loadingEsg, setLoadingEsg] = useState(false);

  const [intelSubTab, setIntelSubTab] = useState<'market' | 'modeling' | 'strategy' | 'stewardship' | 'risk' | 'capital' | 'leadership' | 'esg'>('market');

  useEffect(() => {
    dispatch(fetchMetrics({ query: '?limit=12&sort=as_of_at:ASC' }));
    dispatch(fetchAlerts({ query: '?limit=5' }));
    fetchIntelligence();
  }, [dispatch]);

  useEffect(() => {
    if (activeTab === 'intelligence') {
      if (intelSubTab === 'market' && !intelligence) fetchIntelligence();
      if (intelSubTab === 'modeling' && !modeling) fetchModeling();
      if (intelSubTab === 'strategy' && !opportunities) fetchOpportunities();
      if (intelSubTab === 'stewardship' && !stewardship) fetchStewardship();
      if (intelSubTab === 'risk' && !risk) fetchRisk();
      if (intelSubTab === 'capital' && !capital) fetchCapital();
      if (intelSubTab === 'leadership' && !leadership) fetchLeadership();
      if (intelSubTab === 'esg' && !esg) fetchEsg();
    }
  }, [activeTab, intelSubTab]);

  const fetchIntelligence = async () => {
    setLoadingIntelligence(true);
    try {
      const response = await axios.get('/intelligence');
      setIntelligence(response.data);
    } catch (error) {
      console.error('Failed to fetch intelligence:', error);
    } finally {
      setLoadingIntelligence(false);
    }
  };

  const fetchModeling = async () => {
    setLoadingModeling(true);
    try {
      const response = await axios.get('/intelligence/modeling');
      setModeling(response.data);
    } catch (error) {
      console.error('Failed to fetch modeling:', error);
    } finally {
      setLoadingModeling(false);
    }
  };

  const fetchOpportunities = async () => {
    setLoadingOpportunities(true);
    try {
      const response = await axios.get('/intelligence/opportunities');
      setOpportunities(response.data);
    } catch (error) {
      console.error('Failed to fetch opportunities:', error);
    } finally {
      setLoadingOpportunities(false);
    }
  };

  const fetchStewardship = async () => {
    setLoadingStewardship(true);
    try {
      const response = await axios.get('/intelligence/stewardship');
      setStewardship(response.data);
    } catch (error) {
      console.error('Failed to fetch stewardship:', error);
    } finally {
      setLoadingStewardship(false);
    }
  };

  const fetchRisk = async () => {
    setLoadingRisk(true);
    try {
      const response = await axios.get('/intelligence/risk');
      setRisk(response.data);
    } catch (error) {
      console.error('Failed to fetch risk:', error);
    } finally {
      setLoadingRisk(false);
    }
  };

  const fetchCapital = async () => {
    setLoadingCapital(true);
    try {
      const response = await axios.get('/intelligence/capital');
      setCapital(response.data);
    } catch (error) {
      console.error('Failed to fetch capital:', error);
    } finally {
      setLoadingCapital(false);
    }
  };

  const fetchLeadership = async () => {
    setLoadingLeadership(true);
    try {
      const response = await axios.get('/intelligence/leadership');
      setLeadership(response.data);
    } catch (error) {
      console.error('Failed to fetch leadership:', error);
    } finally {
      setLoadingLeadership(false);
    }
  };

  const fetchEsg = async () => {
    setLoadingEsg(true);
    try {
      const response = await axios.get('/intelligence/esg');
      setEsg(response.data);
    } catch (error) {
      console.error('Failed to fetch esg:', error);
    } finally {
      setLoadingEsg(false);
    }
  };

  useEffect(() => {
    if (chatResponse && chatResponse.success) {
      const outputText = chatResponse.data?.output?.[0]?.content?.[0]?.text;
      if (outputText) {
        setMessages((prev) => [...prev, { role: 'assistant', content: outputText }]);
      }
    }
  }, [chatResponse]);

  const handleSendMessage = () => {
    if (!chatInput.trim()) return;
    
    const newMessages = [...messages, { role: 'user', content: chatInput }];
    setMessages(newMessages);
    setChatInput('');

    dispatch(aiResponse({
      input: newMessages.map(m => ({ role: m.role, content: m.content })),
      options: { poll_interval: 2, poll_timeout: 60 }
    }));
  };

  const latestMetrics = useMemo(() => metrics_snapshots?.[metrics_snapshots.length - 1] || {}, [metrics_snapshots]);

  const chartData = useMemo(() => {
    const labels = metrics_snapshots.map((m: any) => new Date(m.as_of_at).toLocaleDateString(undefined, { month: 'short', year: '2-digit' }));
    const mrrData = metrics_snapshots.map((m: any) => Number(m.mrr || 0));
    const burnData = metrics_snapshots.map((m: any) => Number(m.net_burn_monthly || 0));

    return {
      labels,
      datasets: [
        {
          label: 'MRR',
          fill: false,
          borderColor: '#10b981', // Emerald 500
          borderWidth: 3,
          data: mrrData,
          tension: 0.4,
        },
        {
          label: 'Net Burn',
          fill: false,
          borderColor: '#3b82f6', // Blue 500
          borderWidth: 3,
          data: burnData,
          tension: 0.4,
        }
      ],
    };
  }, [metrics_snapshots]);

  const competitorData = useMemo(() => {
    const labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
    const industryMrr = [50000, 55000, 58000, 65000, 72000, 80000];
    const ourMrr = [20000, 25000, 32000, 38000, 45000, 52000];

    return {
      labels,
      datasets: [
        {
          label: 'Industry Benchmark (Finance)',
          borderColor: '#94a3b8', // Slate 400
          borderDash: [5, 5],
          data: industryMrr,
          tension: 0.4,
        },
        {
          label: 'Our Company',
          borderColor: '#10b981', // Emerald 500
          data: ourMrr,
          tension: 0.4,
        }
      ],
    };
  }, []);

  return (
    <>
      <Head>
        <title>{getPageTitle('AI Virtual CFO Hub')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={icon.mdiRobotOutline} title="AI Virtual CFO & Advisor" main>
          <div className="flex gap-2">
            <BaseButton
              label="Overview"
              color={activeTab === 'company' ? 'info' : 'white'}
              onClick={() => setActiveTab('company')}
              small
            />
            <BaseButton
              label="Competitors"
              color={activeTab === 'competitors' ? 'info' : 'white'}
              onClick={() => setActiveTab('competitors')}
              small
            />
            <BaseButton
              label="Intelligence Hub"
              color={activeTab === 'intelligence' ? 'info' : 'white'}
              onClick={() => setActiveTab('intelligence')}
              icon={icon.mdiNewspaperVariantOutline}
              small
            />
          </div>
        </SectionTitleLineWithButton>

        {/* Top Summary Row */}
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-4 mb-6">
          <CardBox className="border-l-4 border-emerald-500">
            <p className="text-gray-500 text-xs uppercase font-bold tracking-wider">Monthly Revenue</p>
            <h3 className="text-2xl font-bold mt-1">${Number(latestMetrics.mrr || 0).toLocaleString()}</h3>
            <div className="flex items-center text-xs text-emerald-600 font-semibold mt-1">
              <BaseIcon path={icon.mdiTrendingUp} size={14} className="mr-1" /> +12.5% vs last month
            </div>
          </CardBox>

          <CardBox className="border-l-4 border-blue-500">
            <p className="text-gray-500 text-xs uppercase font-bold tracking-wider">Gross Margin</p>
            <h3 className="text-2xl font-bold mt-1">{latestMetrics.gross_margin_percent || 0}%</h3>
            <div className="flex items-center text-xs text-gray-400 mt-1">
              Industry Avg: 75% (SaaS 2026)
            </div>
          </CardBox>

          <CardBox className="border-l-4 border-orange-500">
            <p className="text-gray-500 text-xs uppercase font-bold tracking-wider">Cash Runway</p>
            <h3 className="text-2xl font-bold mt-1">{latestMetrics.runway_months || 'N/A'} Months</h3>
            <div className="flex items-center text-xs text-orange-600 font-semibold mt-1">
              <BaseIcon path={icon.mdiAlertCircleOutline} size={14} className="mr-1" /> Market shifting to profitability
            </div>
          </CardBox>

          <CardBox className="border-l-4 border-purple-500">
            <p className="text-gray-500 text-xs uppercase font-bold tracking-wider">Burn Multiplier</p>
            <h3 className="text-2xl font-bold mt-1">1.2x</h3>
            <div className="flex items-center text-xs text-blue-600 font-semibold mt-1">
              Target: &lt; 1.5x
            </div>
          </CardBox>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Main Visuals Column */}
          <div className="lg:col-span-2 space-y-6">
            {activeTab === 'company' && (
              <CardBox>
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-xl font-bold">Financial Growth Trend</h2>
                  <div className="flex gap-4 text-sm">
                    <span className="flex items-center"><span className="w-3 h-3 bg-emerald-500 rounded-full mr-2"></span> MRR</span>
                    <span className="flex items-center"><span className="w-3 h-3 bg-blue-500 rounded-full mr-2"></span> Net Burn</span>
                  </div>
                </div>
                <div className="h-80">
                  <ChartLineSample data={chartData} />
                </div>
              </CardBox>
            )}

            {activeTab === 'competitors' && (
              <CardBox>
                <div className="flex items-center justify-between mb-6">
                  <h2 className="text-xl font-bold">Industry Benchmark Comparison</h2>
                  <p className="text-sm text-gray-500 italic">Sector: Finance SaaS</p>
                </div>
                <div className="h-80">
                  <ChartLineSample data={competitorData} />
                </div>
                <div className="mt-6 grid grid-cols-2 gap-4">
                  <div className="p-4 bg-gray-50 dark:bg-dark-800 rounded-lg text-center">
                    <p className="text-sm text-gray-500">Our Growth Rank</p>
                    <p className="text-2xl font-bold text-emerald-600">Top 25%</p>
                  </div>
                  <div className="p-4 bg-gray-50 dark:bg-dark-800 rounded-lg text-center">
                    <p className="text-sm text-gray-500">Efficiency Score</p>
                    <p className="text-2xl font-bold text-blue-600">88/100</p>
                  </div>
                </div>
              </CardBox>
            )}

            {activeTab === 'intelligence' && (
              <div className="space-y-6">
                <CardBox>
                  <div className="flex flex-col md:flex-row md:items-center justify-between mb-4 pb-4 border-b gap-4">
                    <div className="flex items-center">
                        <BaseIcon path={icon.mdiFinance} className="mr-2 text-blue-500" />
                        <h2 className="text-xl font-bold text-blue-600 dark:text-blue-400">CFO Intelligence Hub</h2>
                    </div>
                  </div>
                  <div className="flex flex-wrap gap-1 bg-gray-100 dark:bg-dark-900 p-1 rounded-lg mb-6">
                    <BaseButton
                      label="Market News"
                      color={intelSubTab === 'market' ? 'info' : 'white'}
                      onClick={() => setIntelSubTab('market')}
                      className="border-none shadow-none"
                      small
                    />
                    <BaseButton
                      label="Stewardship"
                      color={intelSubTab === 'stewardship' ? 'info' : 'white'}
                      onClick={() => setIntelSubTab('stewardship')}
                      className="border-none shadow-none"
                      small
                    />
                    <BaseButton
                      label="Risk"
                      color={intelSubTab === 'risk' ? 'info' : 'white'}
                      onClick={() => setIntelSubTab('risk')}
                      className="border-none shadow-none"
                      small
                    />
                    <BaseButton
                      label="Capital"
                      color={intelSubTab === 'capital' ? 'info' : 'white'}
                      onClick={() => setIntelSubTab('capital')}
                      className="border-none shadow-none"
                      small
                    />
                    <BaseButton
                      label="Modeling"
                      color={intelSubTab === 'modeling' ? 'info' : 'white'}
                      onClick={() => setIntelSubTab('modeling')}
                      className="border-none shadow-none"
                      small
                    />
                    <BaseButton
                      label="Strategy"
                      color={intelSubTab === 'strategy' ? 'info' : 'white'}
                      onClick={() => setIntelSubTab('strategy')}
                      className="border-none shadow-none"
                      small
                    />
                    <BaseButton
                      label="Leadership"
                      color={intelSubTab === 'leadership' ? 'info' : 'white'}
                      onClick={() => setIntelSubTab('leadership')}
                      className="border-none shadow-none"
                      small
                    />
                    <BaseButton
                      label="ESG"
                      color={intelSubTab === 'esg' ? 'info' : 'white'}
                      onClick={() => setIntelSubTab('esg')}
                      className="border-none shadow-none"
                      small
                    />
                  </div>
                  
                  {intelSubTab === 'market' && intelligence && (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                      <div className="space-y-4">
                        <h3 className="font-bold text-sm uppercase text-gray-400 tracking-widest mb-2">Latest Trends</h3>
                        {intelligence.external.trends.map((trend: any, idx: number) => (
                          <div key={idx} className="p-4 bg-gray-50 dark:bg-dark-800 rounded-xl border border-gray-100 dark:border-dark-700">
                            <div className="flex justify-between items-start mb-1">
                              <h4 className="font-bold text-blue-500 text-sm">{trend.title}</h4>
                              <span className={`text-[10px] px-2 py-0.5 rounded font-bold ${trend.impact === 'High' ? 'bg-red-100 text-red-600' : 'bg-blue-100 text-blue-600'}`}>{trend.impact} Impact</span>
                            </div>
                            <p className="text-xs text-gray-600 dark:text-gray-400 leading-relaxed">{trend.content}</p>
                          </div>
                        ))}
                      </div>
                      
                      <div className="space-y-4">
                        <h3 className="font-bold text-sm uppercase text-gray-400 tracking-widest mb-2">AI Strategic Analysis</h3>
                        <div className="p-5 bg-blue-600 text-white rounded-2xl shadow-lg relative overflow-hidden">
                          <BaseIcon path={icon.mdiRobot} size={48} className="absolute -right-4 -bottom-4 opacity-10" />
                          <div className="relative z-10 text-sm leading-relaxed whitespace-pre-wrap italic">
                            {intelligence.analysis}
                          </div>
                        </div>
                      </div>
                    </div>
                  )}

                  {intelSubTab === 'stewardship' && (
                    <div className="space-y-4">
                      {loadingStewardship ? (
                        <div className="flex justify-center p-12"><BaseIcon path={icon.mdiLoading} className="animate-spin text-blue-500" size={48} /></div>
                      ) : stewardship ? (
                        <div className="p-6 bg-slate-50 dark:bg-slate-900/10 rounded-2xl border border-slate-100 dark:border-slate-800">
                          <div className="flex items-center mb-4">
                            <BaseIcon path={icon.mdiShieldCheckOutline} className="text-slate-500 mr-2" />
                            <h3 className="font-bold text-lg text-slate-800 dark:text-slate-400">Financial Stewardship & Compliance</h3>
                          </div>
                          <div className="text-sm leading-relaxed whitespace-pre-wrap text-slate-900 dark:text-slate-200">
                            {stewardship.stewardship}
                          </div>
                        </div>
                      ) : (
                        <div className="text-center p-12 text-gray-500">Stewardship report unavailable.</div>
                      )}
                    </div>
                  )}

                  {intelSubTab === 'risk' && (
                    <div className="space-y-4">
                      {loadingRisk ? (
                        <div className="flex justify-center p-12"><BaseIcon path={icon.mdiLoading} className="animate-spin text-blue-500" size={48} /></div>
                      ) : risk ? (
                        <div className="p-6 bg-red-50 dark:bg-red-900/10 rounded-2xl border border-red-100 dark:border-red-800">
                          <div className="flex items-center mb-4">
                            <BaseIcon path={icon.mdiShieldAlertOutline} className="text-red-500 mr-2" />
                            <h3 className="font-bold text-lg text-red-800 dark:text-red-400">Cash Flow & Risk Management</h3>
                          </div>
                          <div className="text-sm leading-relaxed whitespace-pre-wrap text-red-900 dark:text-red-200">
                            {risk.risk}
                          </div>
                        </div>
                      ) : (
                        <div className="text-center p-12 text-gray-500">Risk analysis unavailable.</div>
                      )}
                    </div>
                  )}

                  {intelSubTab === 'capital' && (
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                      <div className="space-y-4">
                        {loadingCapital ? (
                          <div className="flex justify-center p-12"><BaseIcon path={icon.mdiLoading} className="animate-spin text-blue-500" size={48} /></div>
                        ) : capital ? (
                          <div className="p-6 bg-blue-50 dark:bg-blue-900/10 rounded-2xl border border-blue-100 dark:border-blue-800 h-full">
                            <div className="flex items-center mb-4">
                              <BaseIcon path={icon.mdiAccountGroup} className="text-blue-500 mr-2" />
                              <h3 className="font-bold text-lg text-blue-800 dark:text-blue-400">Capital Management Strategy</h3>
                            </div>
                            <div className="text-sm leading-relaxed whitespace-pre-wrap text-blue-900 dark:text-blue-200">
                              {capital.capital}
                            </div>
                          </div>
                        ) : (
                          <div className="text-center p-12 text-gray-500">Capital strategy unavailable.</div>
                        )}
                      </div>

                      <div className="space-y-4">
                        <h3 className="font-bold text-sm uppercase text-gray-400 tracking-widest mb-2">Funding Opportunities</h3>
                        <div className="grid grid-cols-1 gap-4">
                          {intelligence?.external?.funding_partners?.map((partner: any, idx: number) => (
                            <div key={idx} className="p-4 border rounded-xl hover:border-blue-500 transition-colors cursor-pointer group" onClick={() => {
                                setChatInput(`Draft an outreach email for ${partner.name} focusing on our MRR of $${Number(latestMetrics.mrr || 0).toLocaleString()}`);
                            }}>
                              <div className="flex justify-between items-center mb-1">
                                <h4 className="font-bold text-sm group-hover:text-blue-600">{partner.name}</h4>
                                <span className="text-[10px] px-2 py-0.5 bg-gray-100 rounded font-bold text-gray-500">{partner.contact_type}</span>
                              </div>
                              <div className="flex flex-wrap gap-2 mt-2">
                                <span className="text-[10px] text-blue-600 bg-blue-50 px-2 py-0.5 rounded italic">{partner.focus}</span>
                                <span className="text-[10px] text-gray-500 bg-gray-50 px-2 py-0.5 rounded">{partner.stage}</span>
                              </div>
                            </div>
                          ))}
                        </div>
                        <BaseButton
                            label="Match me with more investors"
                            icon={icon.mdiHandshakeOutline}
                            color="info"
                            className="w-full"
                            onClick={() => {
                                setChatInput("Search for VC and Angel investors specialized in Fintech and SaaS for a Seed/Series A round in 2026.");
                                handleSendMessage();
                            }}
                        />
                      </div>
                    </div>
                  )}

                  {intelSubTab === 'modeling' && (
                    <div className="space-y-4">
                      {loadingModeling ? (
                        <div className="flex justify-center p-12"><BaseIcon path={icon.mdiLoading} className="animate-spin text-blue-500" size={48} /></div>
                      ) : modeling ? (
                        <div className="p-6 bg-emerald-50 dark:bg-emerald-900/10 rounded-2xl border border-emerald-100 dark:border-emerald-800">
                          <div className="flex items-center mb-4">
                            <BaseIcon path={icon.mdiChartBoxOutline} className="text-emerald-500 mr-2" />
                            <h3 className="font-bold text-lg text-emerald-800 dark:text-emerald-400">Investment Banking Modeling Pack</h3>
                          </div>
                          <div className="text-sm leading-relaxed whitespace-pre-wrap text-emerald-900 dark:text-emerald-200">
                            {modeling.model}
                          </div>
                        </div>
                      ) : (
                        <div className="text-center p-12 text-gray-500">Modeling pack unavailable.</div>
                      )}
                    </div>
                  )}

                  {intelSubTab === 'strategy' && (
                    <div className="space-y-4">
                      {loadingOpportunities ? (
                        <div className="flex justify-center p-12"><BaseIcon path={icon.mdiLoading} className="animate-spin text-blue-500" size={48} /></div>
                      ) : opportunities ? (
                        <div className="p-6 bg-purple-50 dark:bg-purple-900/10 rounded-2xl border border-purple-100 dark:border-purple-800">
                          <div className="flex items-center mb-4">
                            <BaseIcon path={icon.mdiTrophyOutline} className="text-purple-500 mr-2" />
                            <h3 className="font-bold text-lg text-purple-800 dark:text-purple-400">Capitalization & M&A Strategy</h3>
                          </div>
                          <div className="text-sm leading-relaxed whitespace-pre-wrap text-purple-900 dark:text-purple-200">
                            {opportunities.opportunities}
                          </div>
                        </div>
                      ) : (
                        <div className="text-center p-12 text-gray-500">Strategy report unavailable.</div>
                      )}
                    </div>
                  )}

                  {intelSubTab === 'leadership' && (
                    <div className="space-y-4">
                      {loadingLeadership ? (
                        <div className="flex justify-center p-12"><BaseIcon path={icon.mdiLoading} className="animate-spin text-blue-500" size={48} /></div>
                      ) : leadership ? (
                        <div className="p-6 bg-amber-50 dark:bg-amber-900/10 rounded-2xl border border-amber-100 dark:border-amber-800">
                          <div className="flex items-center mb-4">
                            <BaseIcon path={icon.mdiAccountStarOutline} className="text-amber-500 mr-2" />
                            <h3 className="font-bold text-lg text-amber-800 dark:text-amber-400">Strategic Leadership & Board Advisory</h3>
                          </div>
                          <div className="text-sm leading-relaxed whitespace-pre-wrap text-amber-900 dark:text-amber-200">
                            {leadership.leadership}
                          </div>
                        </div>
                      ) : (
                        <div className="text-center p-12 text-gray-500">Leadership advisory unavailable.</div>
                      )}
                    </div>
                  )}

                  {intelSubTab === 'esg' && (
                    <div className="space-y-4">
                      {loadingEsg ? (
                        <div className="flex justify-center p-12"><BaseIcon path={icon.mdiLoading} className="animate-spin text-blue-500" size={48} /></div>
                      ) : esg ? (
                        <div className="p-6 bg-green-50 dark:bg-green-900/10 rounded-2xl border border-green-100 dark:border-green-800">
                          <div className="flex items-center mb-4">
                            <BaseIcon path={icon.mdiLeaf} className="text-green-500 mr-2" />
                            <h3 className="font-bold text-lg text-green-800 dark:text-green-400">ESG Strategy & Impact Reporting</h3>
                          </div>
                          <div className="text-sm leading-relaxed whitespace-pre-wrap text-green-900 dark:text-green-200">
                            {esg.esg}
                          </div>
                        </div>
                      ) : (
                        <div className="text-center p-12 text-gray-500">ESG strategy unavailable.</div>
                      )}
                    </div>
                  )}
                </CardBox>
              </div>
            )}

            {/* AI Advisor Chat (Unified for all tabs) */}
            <CardBox className="flex flex-col h-[450px]">
              <div className="flex items-center mb-4 pb-4 border-b">
                <BaseIcon path={icon.mdiChatProcessing} className="mr-2 text-blue-500" />
                <h2 className="text-lg font-bold">Ask Your AI CFO</h2>
              </div>
              
              <div className="flex-grow overflow-y-auto space-y-4 mb-4 p-2 scrollbar-thin scrollbar-thumb-gray-200">
                {messages.map((m, i) => (
                  <div key={i} className={`flex ${m.role === 'user' ? 'justify-end' : 'justify-start'}`}>
                    <div className={`max-w-[85%] p-4 rounded-2xl shadow-sm ${
                      m.role === 'user' 
                        ? 'bg-blue-600 text-white rounded-tr-none' 
                        : 'bg-white dark:bg-dark-800 border border-gray-100 dark:border-dark-700 text-gray-800 dark:text-gray-200 rounded-tl-none'
                    }`}>
                      <p className="text-sm leading-relaxed whitespace-pre-wrap">{m.content}</p>
                    </div>
                  </div>
                ))}
                {isAskingResponse && (
                  <div className="flex justify-start">
                    <div className="bg-gray-100 dark:bg-dark-800 p-4 rounded-2xl rounded-tl-none animate-pulse">
                      <div className="flex gap-1">
                        <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                        <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce [animation-delay:0.2s]"></div>
                        <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce [animation-delay:0.4s]"></div>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              <div className="mt-auto pt-4 flex gap-2">
                <input
                  type="text"
                  className="flex-grow bg-gray-100 dark:bg-dark-900 border-none rounded-full px-5 py-3 text-sm focus:ring-2 focus:ring-blue-500"
                  placeholder="How can we optimize our R&D tax credits?"
                  value={chatInput}
                  onChange={(e) => setChatInput(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handleSendMessage()}
                />
                <BaseButton
                  icon={icon.mdiSend}
                  color="info"
                  roundedFull
                  onClick={handleSendMessage}
                  disabled={isAskingResponse || !chatInput.trim()}
                />
              </div>
            </CardBox>
          </div>

          {/* Side Column: Alerts & Insights */}
          <div className="lg:col-span-1 space-y-6">
            <CardBox isHoverable>
              <div className="flex items-center mb-4">
                <BaseIcon path={icon.mdiLightningBolt} className="mr-2 text-yellow-500" />
                <h2 className="text-lg font-bold">CFO Strategic Insights</h2>
              </div>
              <div className="space-y-4">
                {alerts.length === 0 ? (
                  <p className="text-gray-500 italic text-sm">Scanning for insights...</p>
                ) : (
                  alerts.slice(0, 3).map((alert: any) => (
                    <div key={alert.id} className="group cursor-pointer" onClick={() => {
                        const prompt = `Act as a CFO: Explain the financial impact of this alert: ${alert.title || alert.description}`;
                        setChatInput(prompt);
                    }}>
                        <div className="flex items-center justify-between mb-1">
                            <span className="text-[10px] uppercase font-bold text-orange-500 bg-orange-50 px-2 py-0.5 rounded">Action Required</span>
                            <span className="text-[10px] text-gray-400">{new Date(alert.createdAt).toLocaleDateString()}</span>
                        </div>
                        <p className="text-sm font-bold group-hover:text-blue-500 transition-colors">{alert.title || alert.type}</p>
                        <p className="text-xs text-gray-500 line-clamp-2 mt-1">{alert.description || alert.message}</p>
                    </div>
                  ))
                )}
              </div>
            </CardBox>

            <CardBox isHoverable>
                <div className="flex items-center mb-4">
                    <BaseIcon path={icon.mdiShieldCheckOutline} className="mr-2 text-blue-500" />
                    <h2 className="text-lg font-bold">Compliance Status</h2>
                </div>
                <div className="space-y-4">
                    <div className="flex justify-between items-center text-sm">
                        <span className="text-gray-500">Audit Readiness</span>
                        <span className="font-bold text-emerald-600">85%</span>
                    </div>
                    <div className="w-full bg-gray-100 rounded-full h-1.5">
                        <div className="bg-emerald-500 h-1.5 rounded-full w-[85%]"></div>
                    </div>
                    
                    <div className="flex justify-between items-center text-sm">
                        <span className="text-gray-500">Tax Compliance</span>
                        <span className={`font-bold text-blue-600`}>100%</span>
                    </div>
                    <div className="w-full bg-gray-100 rounded-full h-1.5">
                        <div className={`h-1.5 rounded-full bg-blue-500`} style={{ width: `100%` }}></div>
                    </div>

                    <div className="mt-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg text-xs text-blue-700 dark:text-blue-300">
                        <strong>CFO Note:</strong> You are currently aligned with 2026 SEC AI Disclosure requirements. Next audit scheduled for Q3.
                    </div>
                </div>
            </CardBox>

            <CardBox>
              <h2 className="text-lg font-bold mb-4">CFO Strategy Actions</h2>
              <div className="space-y-3">
                <BaseButton
                    label="Analyze Risk"
                    icon={icon.mdiShieldAlertOutline}
                    className="w-full text-left"
                    onClick={() => { setActiveTab('intelligence'); setIntelSubTab('risk'); }}
                    small
                />
                <BaseButton
                    label="Fundraising Match"
                    icon={icon.mdiAccountGroup}
                    className="w-full text-left"
                    onClick={() => { setActiveTab('intelligence'); setIntelSubTab('capital'); }}
                    small
                />
                <BaseButton
                    label="ESG Strategy"
                    icon={icon.mdiLeafOutline}
                    className="w-full text-left"
                    onClick={() => { setActiveTab('intelligence'); setIntelSubTab('esg'); }}
                    small
                />
                <BaseButton
                    label="Audit Checklist"
                    icon={icon.mdiClipboardCheckOutline}
                    className="w-full text-left"
                    onClick={() => { setActiveTab('intelligence'); setIntelSubTab('stewardship'); }}
                    small
                />
              </div>
            </CardBox>
          </div>
        </div>
      </SectionMain>
    </>
  );
};

AdvisorPage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default AdvisorPage;