const { useState, useMemo, useEffect, useRef } = React;

/* ============================================================
   Funding Intelligence Tool — Sampoorna Intelligence
   Interactive tool for NGO directors to find matched funders
   ============================================================ */

const SECTORS = [
  'Education', 'Health & Nutrition', 'Rural Development', 'Livelihoods',
  'Women & Girls', 'Skill Development', 'Water, Sanitation & Hygiene',
  'Environment', 'Menstrual Health', 'Disability & Special Needs',
  'Culture, Heritage & Crafts',
];

const STATES = [
  'Pan-India', 'Karnataka', 'Tamil Nadu', 'Jharkhand', 'Rajasthan',
  'Maharashtra', 'Gujarat', 'Uttar Pradesh', 'Odisha', 'Assam',
  'Madhya Pradesh', 'Haryana', 'Andhra Pradesh', 'Bihar', 'Punjab',
  'Telangana', 'West Bengal', 'Goa', 'North East India', 'Delhi',
  'Mizoram', 'Chhattisgarh', 'Uttarakhand', 'Sikkim', 'Ladakh',
  'Manipur', 'Kerala', 'Jammu & Kashmir',
];

const BUDGET_RANGES = [
  { value: 'micro', label: 'Under ₹10 lakh', min: 0, max: 0.1 },
  { value: 'small', label: '₹10 lakh – ₹1 Cr', min: 0.1, max: 1 },
  { value: 'medium', label: '₹1 Cr – ₹10 Cr', min: 1, max: 10 },
  { value: 'large', label: '₹10 Cr – ₹50 Cr', min: 10, max: 50 },
  { value: 'very_large', label: 'Above ₹50 Cr', min: 50, max: 999 },
];

const NGO_AGES = [
  { value: 'new', label: '0–3 years (New)' },
  { value: 'growing', label: '3–9 years (Growing)' },
  { value: 'established', label: '10+ years (Established)' },
];

function formatCr(val) {
  if (val >= 1000) return '₹' + (val / 1000).toFixed(1) + 'K Cr';
  if (val >= 100) return '₹' + Math.round(val) + ' Cr';
  if (val >= 10) return '₹' + val.toFixed(1) + ' Cr';
  return '₹' + val.toFixed(2) + ' Cr';
}

function formatNum(val) {
  if (val >= 1000) return (val / 1000).toFixed(1) + 'K';
  return Math.round(val).toString();
}

/* --- Logo --- */
function Logo() {
  return React.createElement('a', { className: 'fi-nav-logo', href: '/', 'aria-label': 'Sampoorna Intelligence home' },
    React.createElement('svg', { viewBox: '0 0 64 64' },
      React.createElement('circle', { cx: 32, cy: 32, r: 29, fill: 'none', stroke: '#9bc3aa', strokeWidth: 1.2, opacity: 0.7 }),
      React.createElement('ellipse', { cx: 14, cy: 32, rx: 11, ry: 5, fill: '#9bc3aa' }),
      React.createElement('ellipse', { cx: 50, cy: 32, rx: 11, ry: 5, fill: '#9bc3aa' }),
      React.createElement('ellipse', { cx: 32, cy: 14, rx: 5, ry: 11, fill: '#2d6a4f' }),
      React.createElement('ellipse', { cx: 32, cy: 50, rx: 5, ry: 11, fill: '#2d6a4f' }),
      React.createElement('circle', { cx: 32, cy: 32, r: 4.2, fill: '#2d6a4f' }),
      React.createElement('circle', { cx: 32, cy: 32, r: 2, fill: '#f4f0e3' }),
    ),
    'sampoorna'
  );
}

/* --- Nav --- */
function NavBar() {
  return React.createElement('nav', { className: 'fi-nav' },
    React.createElement(Logo),
    React.createElement('div', { className: 'fi-nav-links' },
      React.createElement('a', { href: '/' }, 'Home'),
      React.createElement('a', { href: '/insights/' }, 'Insights'),
      React.createElement('a', { href: '/#chapter-v' }, 'How It Works'),
      React.createElement('a', { href: '/#chapter-x' }, 'Contact'),
      React.createElement('a', { href: (window.SAMPOORNA_URLS && window.SAMPOORNA_URLS.appLoginHref) ? window.SAMPOORNA_URLS.appLoginHref() : 'https://app.sampoornaintelligence.com/login', className: 'btn btn-secondary btn-sm' }, 'Open workspace'),
    )
  );
}

/* --- Stats Band --- */
function StatsBand({ data }) {
  const t = data.totals;
  return React.createElement('div', { className: 'fi-stats' },
    React.createElement('div', { className: 'fi-stat' },
      React.createElement('div', { className: 'fi-stat-num tnum' }, formatNum(t.total_tracked_cr) + ' Cr'),
      React.createElement('div', { className: 'fi-stat-label' }, 'Tracked Funding'),
    ),
    React.createElement('div', { className: 'fi-stat' },
      React.createElement('div', { className: 'fi-stat-num tnum' }, t.total_foundations),
      React.createElement('div', { className: 'fi-stat-label' }, 'Foundations'),
    ),
    React.createElement('div', { className: 'fi-stat' },
      React.createElement('div', { className: 'fi-stat-num tnum' }, t.total_grants),
      React.createElement('div', { className: 'fi-stat-label' }, 'Grants'),
    ),
    React.createElement('div', { className: 'fi-stat' },
      React.createElement('div', { className: 'fi-stat-num tnum' }, t.total_ngos),
      React.createElement('div', { className: 'fi-stat-label' }, 'NGOs Funded'),
    ),
  );
}

/* --- Form Field --- */
function Field({ label, children }) {
  return React.createElement('div', { className: 'fi-field' },
    React.createElement('label', { className: 'label' }, label),
    children,
  );
}

/* --- Results: Matched Funders Card --- */
function MatchedFundersCard({ sector, state, data }) {
  const matched = useMemo(() => {
    return data.foundations.filter(f => {
      const sectorMatch = f.focus_areas.some(a => a === sector || a.includes(sector.split(',')[0]));
      const stateMatch = !state || state === 'Pan-India' ||
        (f.geography && f.geography.includes(state)) ||
        f.geography.includes('Pan-India');
      return sectorMatch && stateMatch;
    });
  }, [sector, state, data]);

  const openCount = matched.filter(f => f.application_type === 'open' || f.application_type === 'both').length;

  return React.createElement('div', { className: 'fi-result-card' },
    React.createElement('h4', null, 'Matched Foundations'),
    React.createElement('p', { style: { fontSize: 13, color: 'var(--ink-2)' } },
      matched.length + ' foundations fund ' + sector + ' in ' + state,
    ),
    React.createElement('div', { className: 'fi-result-metrics' },
      React.createElement('div', { className: 'fi-result-metric' },
        React.createElement('div', { className: 'fi-result-metric-val' }, matched.length),
        React.createElement('div', { className: 'fi-result-metric-label' }, 'Matched'),
      ),
      React.createElement('div', { className: 'fi-result-metric' },
        React.createElement('div', { className: 'fi-result-metric-val' }, openCount),
        React.createElement('div', { className: 'fi-result-metric-label' }, 'Open Apps'),
      ),
      React.createElement('div', { className: 'fi-result-metric' },
        React.createElement('div', { className: 'fi-result-metric-val' }, matched.filter(f => f.type === 'Corporate').length),
        React.createElement('div', { className: 'fi-result-metric-label' }, 'Corporate'),
      ),
    ),
  );
}

/* --- Results: Sector Funding Card --- */
function SectorFundingCard({ sector, data }) {
  const sectorData = data.sectors.find(s => s.focus_area === sector);
  if (!sectorData) return null;

  const grantRatio = sectorData.unique_ngos > 0
    ? (sectorData.grant_count / sectorData.unique_ngos).toFixed(1)
    : '—';

  return React.createElement('div', { className: 'fi-result-card' },
    React.createElement('h4', null, 'Funding Landscape: ' + sector),
    React.createElement('div', { className: 'fi-result-metrics' },
      React.createElement('div', { className: 'fi-result-metric' },
        React.createElement('div', { className: 'fi-result-metric-val' }, formatCr(sectorData.total_cr)),
        React.createElement('div', { className: 'fi-result-metric-label' }, 'Total Funding'),
      ),
      React.createElement('div', { className: 'fi-result-metric' },
        React.createElement('div', { className: 'fi-result-metric-val' }, sectorData.grant_count),
        React.createElement('div', { className: 'fi-result-metric-label' }, 'Grants'),
      ),
      React.createElement('div', { className: 'fi-result-metric' },
        React.createElement('div', { className: 'fi-result-metric-val' }, sectorData.unique_funders),
        React.createElement('div', { className: 'fi-result-metric-label' }, 'Funders'),
      ),
    ),
    React.createElement('div', { style: { marginTop: 12, fontSize: 12, color: 'var(--ink-3)' } },
      React.createElement('span', null, sectorData.unique_ngos + ' recipient NGOs · '),
      React.createElement('strong', { style: { color: 'var(--brand)' } }, grantRatio + ' grants per NGO'),
    ),
  );
}

/* --- Results: State Funding Card --- */
function StateFundingCard({ state, data }) {
  const stateData = data.states.find(s => s.state === state);
  if (!stateData) return null;

  const allStateCr = data.states.reduce((sum, s) => sum + s.total_cr, 0);
  const sharePct = ((stateData.total_cr / allStateCr) * 100).toFixed(1);

  return React.createElement('div', { className: 'fi-result-card' },
    React.createElement('h4', null, 'Geographic Analysis: ' + state),
    React.createElement('div', { className: 'fi-result-metrics' },
      React.createElement('div', { className: 'fi-result-metric' },
        React.createElement('div', { className: 'fi-result-metric-val' }, formatCr(stateData.total_cr)),
        React.createElement('div', { className: 'fi-result-metric-label' }, 'Funding Received'),
      ),
      React.createElement('div', { className: 'fi-result-metric' },
        React.createElement('div', { className: 'fi-result-metric-val' }, sharePct + '%'),
        React.createElement('div', { className: 'fi-result-metric-label' }, 'Share of Total'),
      ),
      React.createElement('div', { className: 'fi-result-metric' },
        React.createElement('div', { className: 'fi-result-metric-val' }, stateData.unique_funders),
        React.createElement('div', { className: 'fi-result-metric-label' }, 'Active Funders'),
      ),
    ),
  );
}

/* --- Results: Risk Assessment Card --- */
function RiskAssessmentCard({ budgetRange, ngoAge }) {
  let riskLevel = 'Moderate';
  let riskColor = 'var(--c-amber)';
  let riskText = 'Based on sector benchmarks, NGOs your size have a moderate risk of funding deficit.';

  if (budgetRange === 'micro' || budgetRange === 'small') {
    riskLevel = 'High';
    riskColor = 'var(--c-coral)';
    riskText = 'Micro and small NGOs often report funding deficits. Diversifying your funder base is critical.';
  } else if (budgetRange === 'medium') {
    riskLevel = 'Moderate';
    riskColor = 'var(--c-amber)';
    riskText = 'Medium-sized NGOs frequently report funding deficits. Multi-year contracts and corpus building are key.';
  } else {
    riskLevel = 'Lower';
    riskColor = 'var(--c-emerald)';
    riskText = 'Larger NGOs report fewer funding deficits, but face challenges in talent and governance.';
  }

  if (ngoAge === 'new') {
    riskText += ' As a newer NGO, building funder relationships early is essential — most funders prefer 3+ year track records.';
  }

  return React.createElement('div', { className: 'fi-result-card' },
    React.createElement('h4', null, 'Funding Deficit Risk'),
    React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, marginTop: 8 } },
      React.createElement('div', { style: {
        padding: '4px 12px', borderRadius: 'var(--r-pill)',
        background: riskColor + '20', color: riskColor,
        fontSize: 12, fontWeight: 600,
      } }, riskLevel),
      React.createElement('span', { style: { fontSize: 12, color: 'var(--ink-3)' } }, 'Based on pan-India NGO survey data'),
    ),
    React.createElement('p', { style: { fontSize: 12, color: 'var(--ink-2)', marginTop: 10, lineHeight: 1.5 } }, riskText),
  );
}

/* --- Locked Section --- */
function LockedSection({ title, preview }) {
  return React.createElement('div', { className: 'fi-locked' },
    React.createElement('div', { className: 'fi-locked-content' },
      React.createElement('h4', { style: { fontSize: 14, marginBottom: 8 } }, title),
      React.createElement('div', { style: { fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.6 } }, preview),
    ),
    React.createElement('div', { className: 'fi-locked-veil' },
      React.createElement('svg', { className: 'lock-icon', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5 },
        React.createElement('rect', { x: 5, y: 11, width: 14, height: 10, rx: 2 }),
        React.createElement('path', { d: 'M8 11V7a4 4 0 0 1 8 0v4' }),
      ),
      React.createElement('p', null, 'Available in your personalized intelligence brief'),
    ),
  );
}

/* --- Results Panel --- */
function ResultsPanel({ sector, state, budgetRange, ngoAge, data, onSubmit, submitted }) {
  if (!sector || !state) {
    return React.createElement('div', { className: 'fi-results' },
      React.createElement('div', { className: 'fi-results-empty' },
        React.createElement('svg', { viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1 },
          React.createElement('circle', { cx: 11, cy: 11, r: 8 }),
          React.createElement('path', { d: 'M21 21l-4.35-4.35' }),
        ),
        React.createElement('p', { style: { fontSize: 14 } }, 'Select your sector and state to see your funding landscape'),
      ),
    );
  }

  if (submitted) {
    return React.createElement('div', { className: 'fi-results' },
      React.createElement('div', { className: 'fi-success' },
        React.createElement('svg', { viewBox: '0 0 24 24', fill: 'none', stroke: 'var(--brand)', strokeWidth: 1.5 },
          React.createElement('circle', { cx: 12, cy: 12, r: 10 }),
          React.createElement('path', { d: 'M9 12l2 2 4-4' }),
        ),
        React.createElement('h3', null, 'Your brief is on its way'),
        React.createElement('p', null, 'We are preparing your personalized NGO Intelligence Brief and will send it to your inbox shortly. Check your email in the next few minutes.'),
      ),
    );
  }

  return React.createElement('div', { className: 'fi-results' },
    React.createElement('div', { style: { marginBottom: 20 } },
      React.createElement('span', { className: 'eyebrow' }, 'Your Funding Landscape'),
      React.createElement('h3', { style: { fontSize: 20, marginTop: 8 } },
        sector + ' · ' + state,
      ),
    ),
    React.createElement(MatchedFundersCard, { sector, state, data }),
    React.createElement(SectorFundingCard, { sector, data }),
    React.createElement(StateFundingCard, { state, data }),
    React.createElement(RiskAssessmentCard, { budgetRange, ngoAge }),
    React.createElement(LockedSection, {
      title: 'Your Top 5 Matched Funders',
      preview: 'Your top matched funders will appear here — including each funder’s sector focus, application posture, and indicative grant range, filtered to your profile.',
    }),
    React.createElement(LockedSection, {
      title: 'Your Personalized Outreach Strategy',
      preview: 'Based on your profile, here is a recommended approach:\n\n1. Start with open-application funders that accept unsolicited proposals in your sector.\n\n2. For invite-only funders, build visibility through sector events and NGO directories before approaching.\n\n3. Timing matters: most CSR committees meet in Oct–Dec. Begin outreach in August for the next funding cycle.\n\n4. Position your proposal around measurable outcomes — funders in this sector prioritise impact evidence over activity lists.',
    }),
    React.createElement(LockedSection, {
      title: 'Funding Diversification Roadmap',
      preview: 'Your current risk profile suggests over-reliance on a single funder type. Here is a 12-month diversification plan:\n\nPhase 1 (Months 1–3): Secure corporate CSR funders through open applications\nPhase 2 (Months 4–6): Approach philanthropic foundations for multi-year support\nPhase 3 (Months 7–9): Build relationships with invite-only funders\nPhase 4 (Months 10–12): Explore international funding opportunities\n\nTarget: a broader base of active funder relationships within 12 months',
    }),
  );
}

/* --- Lead Capture Form --- */
function LeadCaptureForm({ sector, state, budgetRange, ngoAge, onSubmit }) {
  const [form, setForm] = useState({ name: '', ngoName: '', email: '', phone: '' });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.ngoName || !form.email) {
      setError('Please fill in your name, NGO name, and email.');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const resp = await fetch('/api/funding-brief', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...form,
          sector, state, budgetRange, ngoAge,
        }),
      });
      if (resp.ok) {
        onSubmit();
      } else {
        setError('Something went wrong. Please try again or email us directly.');
      }
    } catch (err) {
      setError('Network error. Please check your connection and try again.');
    }
    setLoading(false);
  };

  return React.createElement('div', { className: 'fi-capture' },
    React.createElement('h3', null, 'Get Your Free NGO Intelligence Brief'),
    React.createElement('p', null, 'We will prepare a personalized brief with your top matched funders, outreach strategy, and funding diversification roadmap — and email it to you.'),
    error && React.createElement('p', { style: { color: 'var(--c-coral)', fontSize: 13, marginBottom: 12 } }, error),
    React.createElement('form', { onSubmit: handleSubmit },
      React.createElement('div', { className: 'fi-capture-row' },
        React.createElement('input', {
          className: 'input', placeholder: 'Your name',
          value: form.name,
          onChange: e => setForm({ ...form, name: e.target.value }),
        }),
        React.createElement('input', {
          className: 'input', placeholder: 'NGO name',
          value: form.ngoName,
          onChange: e => setForm({ ...form, ngoName: e.target.value }),
        }),
      ),
      React.createElement('div', { className: 'fi-capture-row' },
        React.createElement('input', {
          className: 'input', type: 'email', placeholder: 'Email address',
          value: form.email,
          onChange: e => setForm({ ...form, email: e.target.value }),
        }),
        React.createElement('input', {
          className: 'input', type: 'tel', placeholder: 'Phone (optional)',
          value: form.phone,
          onChange: e => setForm({ ...form, phone: e.target.value }),
        }),
      ),
      React.createElement('button', {
        type: 'submit',
        className: 'btn btn-primary btn-lg',
        disabled: loading,
      }, loading ? 'Preparing your brief...' : 'Send My Intelligence Brief'),
    ),
  );
}

/* --- Sampoorna CTA --- */
function SampoornaCTA() {
  return React.createElement('div', { className: 'fi-sampoorna-cta' },
    React.createElement('h2', null, 'This is just the beginning'),
    React.createElement('p', null,
      'Sampoorna Intelligence builds detailed funder intelligence briefs across CSR, foundations, and international sources — with a matching engine and personalised outreach playbooks. The free tool above gives a taste of the intelligence; the full platform goes far deeper.',
    ),
    React.createElement('div', { style: { display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' } },
      React.createElement('a', {
        href: (window.SAMPOORNA_URLS && window.SAMPOORNA_URLS.appLoginHref) ? window.SAMPOORNA_URLS.appLoginHref() : 'https://app.sampoornaintelligence.com/login',
        className: 'btn btn-lg',
      }, 'Start 14-day free trial'),
      React.createElement('a', { href: '/#chapter-x', className: 'btn btn-secondary btn-lg', style: { background: 'transparent', color: '#fff', borderColor: 'rgba(255,255,255,0.3)' } }, 'Talk to the Founders'),
    ),
  );
}

/* --- Footer --- */
function Footer() {
  return React.createElement('footer', { className: 'fi-footer' },
    React.createElement('p', null, 'Sampoorna Intelligence · Funding intelligence for Indian NGOs'),
    React.createElement('div', { style: { display: 'flex', gap: 20 } },
      React.createElement('a', { href: '/' }, 'Home'),
      React.createElement('a', { href: '/insights/' }, 'Insights'),
      React.createElement('a', { href: 'mailto:founder@sampoornaintelligence.com' }, 'Contact'),
    ),
  );
}

/* --- Main App --- */
function FundingIntelligenceApp() {
  const data = window.FUNDING_INTELLIGENCE_DATA || { foundations: [], sectors: [], states: [], totals: {} };
  const [sector, setSector] = useState('');
  const [state, setState] = useState('');
  const [budgetRange, setBudgetRange] = useState('small');
  const [ngoAge, setNgoAge] = useState('growing');
  const [submitted, setSubmitted] = useState(false);

  const showResults = sector && state;
  const showForm = showResults && !submitted;

  // Scroll reveal
  useEffect(() => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('revealed'); });
    }, { threshold: 0.1 });
    document.querySelectorAll('.scroll-reveal').forEach(el => observer.observe(el));
    return () => observer.disconnect();
  }, [showResults, submitted]);

  return React.createElement('div', { className: 'fi-page' },
    React.createElement(NavBar),
    React.createElement('section', { className: 'fi-hero scroll-reveal' },
      React.createElement('span', { className: 'eyebrow' }, 'Free Tool · Funding Intelligence'),
      React.createElement('h1', null, 'Find funders matched to your NGO'),
      React.createElement('p', null,
        'Select your sector and geography to see your funding landscape — matched foundations, peer context, and risk assessment. Then get a personalized intelligence brief delivered to your inbox.',
      ),
    ),
    React.createElement('div', { className: 'scroll-reveal' },
      React.createElement(StatsBand, { data }),
    ),
    React.createElement('section', { className: 'fi-tool-section scroll-reveal' },
      React.createElement('div', { className: 'fi-tool-grid' },
        /* Left: Form inputs */
        React.createElement('div', { className: 'fi-form-card' },
          React.createElement('h3', null, 'Tell us about your NGO'),
          React.createElement('p', { className: 'fi-form-sub' }, 'We will analyze the funding landscape for your specific profile.'),
          React.createElement(Field, { label: 'Your Sector' },
            React.createElement('select', {
              className: 'fi-select', value: sector,
              onChange: e => setSector(e.target.value),
            },
              React.createElement('option', { value: '' }, 'Select your primary sector...'),
              SECTORS.map(s => React.createElement('option', { key: s, value: s }, s)),
            ),
          ),
          React.createElement(Field, { label: 'Your State' },
            React.createElement('select', {
              className: 'fi-select', value: state,
              onChange: e => setState(e.target.value),
            },
              React.createElement('option', { value: '' }, 'Select your primary state...'),
              STATES.map(s => React.createElement('option', { key: s, value: s }, s)),
            ),
          ),
          React.createElement(Field, { label: 'Annual Budget' },
            React.createElement('select', {
              className: 'fi-select', value: budgetRange,
              onChange: e => setBudgetRange(e.target.value),
            },
              BUDGET_RANGES.map(b => React.createElement('option', { key: b.value, value: b.value }, b.label)),
            ),
          ),
          React.createElement(Field, { label: 'NGO Age' },
            React.createElement('select', {
              className: 'fi-select', value: ngoAge,
              onChange: e => setNgoAge(e.target.value),
            },
              NGO_AGES.map(a => React.createElement('option', { key: a.value, value: a.value }, a.label)),
            ),
          ),
          showForm && React.createElement(LeadCaptureForm, {
            sector, state, budgetRange, ngoAge,
            onSubmit: () => setSubmitted(true),
          }),
        ),
        /* Right: Results */
        React.createElement(ResultsPanel, {
          sector, state, budgetRange, ngoAge, data, submitted,
          onSubmit: () => setSubmitted(true),
        }),
      ),
    ),
    React.createElement('div', { className: 'scroll-reveal' },
      React.createElement(SampoornaCTA),
    ),
    React.createElement(Footer),
  );
}

ReactDOM.render(
  React.createElement(FundingIntelligenceApp),
  document.getElementById('app'),
);
