import { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import {
  Compass, TrendingUp, Target, Rocket, Users, Plug,
  Crown, BookOpen, Lightbulb, Landmark, ArrowRight,
  Check, Menu, X, ChevronRight, BarChart3, Zap,
  Award, Shield
} from 'lucide-react';
import { FeatureModal } from '../components/ui/FeatureModal';

// ─── Brand colors ───
const COLORS = {
  bg: '#0a0f1a',
  bgAlt: '#050a14',
  green: '#00A846',
  blue: '#00AECB',
  lime: '#C6F24E',
  red: '#ff4d4d',
  cardBg: 'rgba(255,255,255,0.04)',
  cardBorder: 'rgba(255,255,255,0.1)',
};

// ─── Next Move Card (live coaching insight) ───
function NextMoveCard() {
  const [insight, setInsight] = useState<{ title: string; narrative: string } | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Fetch top coaching insight (public endpoint, no auth required)
    fetch('/api/coaching/insights')
      .then((res) => res.json())
      .then((data: { insights?: Array<{ title: string; narrative: string }> }) => {
        if (data?.insights?.[0]) {
          setInsight(data.insights[0]);
        }
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  // Fallback static message while loading or on error
  const fallback = {
    title: 'Coach the Phoenix market on follow-up speed',
    narrative: 'Recover an estimated $84K this quarter',
  };

  const display = insight || fallback;

  return (
    <div
      className="flex items-start gap-2.5 rounded-xl border p-3"
      style={{ borderColor: `${COLORS.lime}30`, background: `${COLORS.lime}0d` }}
    >
      <span style={{ color: COLORS.lime }}>✦</span>
      <div>
        <div
          className="text-[10px] font-bold uppercase tracking-wider mb-0.5"
          style={{ color: COLORS.lime }}
        >
          Next move
        </div>
        <div className="text-xs text-white/70 leading-snug">
          {loading ? (
            <span className="animate-pulse">Loading insights…</span>
          ) : (
            <>
              {display.title}. {display.narrative}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Shared inline styles ───
const sectionStyle = (extra?: React.CSSProperties): React.CSSProperties => ({
  ...extra,
});

const cardStyle: React.CSSProperties = {
  background: COLORS.cardBg,
  border: `1px solid ${COLORS.cardBorder}`,
  borderRadius: '1rem',
  transition: 'border-color 0.2s',
};

const badgeStyle = (color: string, bgColor: string): React.CSSProperties => ({
  display: 'inline-flex',
  alignItems: 'center',
  gap: '0.5rem',
  padding: '0.375rem 1rem',
  borderRadius: '9999px',
  fontSize: '0.75rem',
  fontWeight: 600,
  color,
  background: bgColor,
  border: `1px solid ${color}`,
  marginBottom: '1.5rem',
});

// ─── Navigation ───
function Navigation() {
  const [open, setOpen] = useState(false);

  const links = [
    { label: 'Why', href: '#why' },
    { label: 'Mission', href: '#manifesto' },
    { label: 'Stories', href: '#stories' },
    { label: 'Pricing', href: '#pricing' },
    { label: 'Docs', href: '#docs' },
  ];

  const handleNav = (href: string) => {
    setOpen(false);
    const el = document.querySelector(href);
    if (el) el.scrollIntoView({ behavior: 'smooth' });
  };

  return (
    <header className="z-50 pt-3 px-4">
      <nav
        className="max-w-6xl mx-auto rounded-full border border-white/10 backdrop-blur-xl pl-5 pr-2.5 h-14 flex items-center justify-between shadow-xl shadow-black/30"
        style={{ background: 'rgba(10,16,28,0.7)' }}
      >
        <Link to="/" className="flex items-center gap-2.5">
          <div
            className="w-7 h-7 rounded-lg flex items-center justify-center font-black text-[11px]"
            style={{ background: COLORS.green }}
          >
            CC
          </div>
          <span className="font-bold tracking-tight">Command Center</span>
        </Link>

        {/* Desktop links */}
        <div className="hidden md:flex items-center gap-7 text-sm text-white/60">
          {links.map((l) => (
            <button
              key={l.href}
              onClick={() => handleNav(l.href)}
              className="hover:text-white transition-colors"
            >
              {l.label}
            </button>
          ))}
        </div>

        <div className="hidden md:flex items-center gap-1 sm:gap-2">
          <Link
            to="/auth/login"
            className="text-sm text-white/70 hover:text-white transition-colors px-3 py-2 min-h-[44px] flex items-center"
          >
            Log in
          </Link>
          <Link
            to="/auth/signup"
            className="px-5 py-2.5 rounded-full text-sm font-semibold transition-all hover:opacity-90 min-h-[44px]"
            style={{ background: COLORS.green }}
          >
            Start free trial
          </Link>
        </div>

        {/* Mobile hamburger */}
        <button
          className="md:hidden p-2 text-white/60 hover:text-white min-w-[44px] min-h-[44px] flex items-center justify-center rounded-lg hover:bg-white/5"
          onClick={() => setOpen(!open)}
        >
          {open ? <X size={20} /> : <Menu size={20} />}
        </button>
      </nav>

      {/* Mobile menu */}
      {open && (
        <div
          className="md:hidden mt-2 mx-4 rounded-2xl border border-white/10 backdrop-blur-xl p-4 space-y-3"
          style={{ background: 'rgba(10,16,28,0.95)' }}
        >
          {links.map((l) => (
            <button
              key={l.href}
              onClick={() => handleNav(l.href)}
              className="block w-full text-left text-sm text-white/60 hover:text-white py-2.5 min-h-[44px]"
            >
              {l.label}
            </button>
          ))}
          <hr className="border-white/10" />
          <Link
            to="/auth/login"
            className="block text-sm text-white/70 hover:text-white py-2"
            onClick={() => setOpen(false)}
          >
            Log in
          </Link>
          <Link
            to="/auth/signup"
            className="block text-center px-4 py-2.5 rounded-full text-sm font-semibold min-h-[44px]"
            style={{ background: COLORS.green }}
            onClick={() => setOpen(false)}
          >
            Start free trial
          </Link>
        </div>
      )}
    </header>
  );
}

// ─── Hero Section ───
function HeroSection() {
  return (
    <section className="relative overflow-hidden pt-16 pb-24 px-6 hero-section">
      {/* Radial gradient background */}
      <div
        className="absolute inset-0 opacity-25"
        style={{
          background:
            'radial-gradient(ellipse at 15% 10%, #00AECB 0%, transparent 55%), radial-gradient(ellipse at 95% 85%, #00A846 0%, transparent 50%)',
        }}
      />

      <div className="relative max-w-6xl mx-auto grid lg:grid-cols-2 gap-12 items-center">
        {/* Text content */}
        <div>
          <div style={badgeStyle(COLORS.lime, `${COLORS.lime}12`)}>
            <span
              className="w-1.5 h-1.5 rounded-full bg-current"
              style={{ animation: 'pulse 2s infinite' }}
            />
            Signal Over Noise · True North for the Trades
          </div>

          <h1 className="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-black leading-[1.04] tracking-tight mb-6">
            Stop hunting<br />
            for the number.<br />
            <span style={{ color: COLORS.lime }}>Command it.</span>
          </h1>

          <p className="text-lg text-white/70 max-w-xl mb-8 leading-relaxed">
            Command Center unifies every tool a home improvement company runs, forecasts
            the quarter, cascades goals to every rep, and tells your leaders exactly what
            to fix next. One clear path from chaos to sovereignty.
          </p>

          <div className="flex flex-wrap items-center gap-3 mb-8">
            <Link
              to="/auth/signup"
              className="group px-8 py-3.5 rounded-full text-base font-bold shadow-lg flex items-center gap-2 hover:opacity-90 transition-opacity min-h-[44px]"
              style={{ background: COLORS.green }}
            >
              Start 7-day free trial
              <ChevronRight size={16} className="transition-transform group-hover:translate-x-0.5" />
            </Link>
            <a
              href="#demo"
              className="px-8 py-3.5 rounded-full text-base font-semibold border border-white/15 hover:border-white/35 transition-colors min-h-[44px]"
            >
              Book a demo
            </a>
          </div>

          <div className="flex items-center gap-3.5 text-sm text-white/50">
            <div className="flex -space-x-2">
              {['MH', 'PN', 'DO'].map((initials) => (
                <div
                  key={initials}
                  className="w-8 h-8 rounded-full flex items-center justify-center text-[10px] font-bold border-2 border-[#0a0f1a]"
                  style={{
                    background: `linear-gradient(135deg, ${COLORS.blue}, ${COLORS.green})`,
                    color: '#001018',
                  }}
                >
                  {initials}
                </div>
              ))}
            </div>
            <span>
              Trusted by operators running{' '}
              <span className="text-white/80 font-semibold">9-figure</span> portfolios
            </span>
          </div>
        </div>

        {/* Dashboard mockup */}
        <div className="relative">
          <div
            className="absolute -inset-6 rounded-[2.5rem] opacity-25 blur-3xl"
            style={{
              background: 'radial-gradient(circle at 70% 25%, #C6F24E, transparent 70%)',
            }}
          />
          <div
            className="relative rounded-3xl border border-white/10 p-5 sm:p-6 shadow-2xl shadow-black/50 backdrop-blur-xl"
            style={{
              background: 'linear-gradient(160deg, rgba(0,48,87,0.55), rgba(10,16,28,0.9))',
            }}
          >
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-2">
                <span className="relative flex h-2 w-2">
                  <span
                    className="absolute inline-flex h-full w-full rounded-full opacity-75"
                    style={{ background: COLORS.lime, animation: 'ping 1.5s cubic-bezier(0, 0, 0.2, 1) infinite' }}
                  />
                  <span
                    className="relative inline-flex rounded-full h-2 w-2"
                    style={{ background: COLORS.lime }}
                  />
                </span>
                <span className="text-[11px] font-bold uppercase tracking-widest text-white/70">
                  Live forecast
                </span>
              </div>
              <span className="text-[11px] font-semibold text-white/40">JUN 2026</span>
            </div>

            <div className="text-[11px] font-semibold uppercase tracking-wider text-white/40 mb-1">
              Projected landing
            </div>
            <div className="flex items-end gap-3 mb-6">
              <div className="text-4xl font-black tracking-tight">$2.41M</div>
              <div
                className="mb-1.5 inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-bold"
                style={{ background: `${COLORS.lime}22`, color: COLORS.lime }}
              >
                On pace · 103%
              </div>
            </div>

            {/* Bar chart */}
            <div className="flex items-end gap-1.5 h-20 mb-6">
              {[42, 55, 48, 63, 70, 66, 82, 78, 91].map((h, i) => (
                <div
                  key={i}
                  className="flex-1 rounded-t-md"
                  style={{
                    height: `${h}%`,
                    background: i >= 7 ? COLORS.lime : `${COLORS.blue}80`,
                  }}
                />
              ))}
            </div>

            {/* Metrics row */}
            <div className="grid grid-cols-3 gap-2 mb-5">
              {[
                { label: 'Close rate', value: '34%' },
                { label: 'CAC', value: '$410' },
                { label: 'Pipeline', value: '$5.1M' },
              ].map((m) => (
                <div
                  key={m.label}
                  className="rounded-xl border border-white/10 p-2.5"
                  style={{ background: 'rgba(255,255,255,0.03)' }}
                >
                  <div className="text-[10px] uppercase tracking-wider text-white/40">
                    {m.label}
                  </div>
                  <div className="text-sm font-bold">{m.value}</div>
                </div>
              ))}
            </div>

            {/* Next move */}
            <NextMoveCard />
          </div>
        </div>
      </div>

      <p className="relative text-center text-xs text-white/55 mt-16">
        No credit card required · Up and running in a day
      </p>
    </section>
  );
}

// ─── Integrations Bar ───
function IntegrationsBar() {
  const integrations = [
    'ServiceTitan', 'JobNimbus', 'HubSpot', 'Google Ads', 'Facebook Ads',
    'Angi', 'HomeAdvisor', 'QuickBooks', 'Slack',
  ];

  return (
    <section
      className="py-8 border-y border-white/10"
      style={{ background: 'rgba(255,255,255,0.03)' }}
    >
      <div className="max-w-5xl mx-auto px-6">
        <p className="text-center text-xs font-semibold uppercase tracking-widest text-white/60 mb-5">
          Connects with your existing tools
        </p>
        <div className="flex flex-wrap items-center justify-center gap-4">
          {integrations.map((name) => (
            <span
              key={name}
              className="px-4 py-2 rounded-lg text-sm font-medium border border-white/10 text-white/60"
              style={{ background: 'rgba(255,255,255,0.05)' }}
            >
              {name}
            </span>
          ))}
          <span className="px-4 py-2 text-sm text-white/60 font-medium">
            + any REST API
          </span>
        </div>
      </div>
    </section>
  );
}

// ─── Manifesto / Mission Section ───
function ManifestoSection() {
  return (
    <section id="manifesto" className="relative overflow-hidden py-12 md:py-24 px-6" style={sectionStyle()}>
      <div
        className="absolute inset-0"
        style={{
          background: 'linear-gradient(160deg, #003057cc 0%, #0a0f1a 50%, #020810 100%)',
        }}
      />
      <div
        className="absolute inset-0 opacity-10"
        style={{
          background: 'radial-gradient(ellipse at 50% 0%, #00AECB 0%, transparent 70%)',
        }}
      />
      <div className="relative max-w-3xl mx-auto">
        <div style={badgeStyle(COLORS.blue, 'transparent')}>Our Mission</div>

        <div className="space-y-6 text-lg md:text-xl leading-relaxed font-medium">
          <p style={{ color: 'rgba(255,255,255,0.90)' }}>
            We see you grinding before sunrise. Chasing close rates. Managing crews across
            three markets. Wondering if this month&apos;s number will land, all while fielding
            calls, running a P&amp;L on a whiteboard, and fighting a dozen disconnected tools
            just to find the truth.
          </p>
          <p style={{ color: 'rgba(255,255,255,0.75)' }}>
            You didn&apos;t build this company to spend your days hunting for a number. You built
            it to build something. A legacy. A team. A livelihood for the people who show up
            for you every day.
          </p>
          <p style={{ color: 'rgba(255,255,255,0.75)' }}>
            The chaos in your stack isn&apos;t just annoying. It&apos;s the thing standing between
            you and your greatness. Every hour lost to reconciling spreadsheets is an hour not
            spent on strategy, on coaching, on growth.
          </p>
          <p
            className="text-base md:text-lg"
            style={{ color: 'rgba(255,255,255,0.60)' }}
          >
            Inspired by Bitcoin&apos;s Lightning ethos of proof of work and signal over noise,
            we built Command Center to give you the clarity to steer. Not another dashboard
            that shows you what happened. A command center that tells you what to do next.
          </p>
          <div className="pt-4 border-t border-white/10">
            <p className="text-xl md:text-2xl font-black" style={{ color: COLORS.green }}>
              You deserve sovereignty. Let&apos;s build it together.
            </p>
          </div>
        </div>
      </div>
    </section>
  );
}

// ─── Features Grid ───
function FeaturesSection() {
  const features = [
    {
      icon: Compass,
      title: 'Strategic Intelligence',
      desc: 'An FP&A waterfall and drillable root-cause tree reconcile every dollar of variance down to the driver.',
    },
    {
      icon: TrendingUp,
      title: 'Forecasting & Run-Rate',
      desc: "Live run-rate vs. required pace, with a projected landing curve. Know if you'll hit the number weeks early.",
    },
    {
      icon: Target,
      title: 'Cascading Goals',
      desc: 'Targets that auto-calculate from the org goal down to each frontline rep: org → department → team → rep.',
    },
    {
      icon: Rocket,
      title: 'Scale Optimization',
      desc: 'ROAS and LTV:CAC ranked by product × channel × market, with recommended budget moves.',
    },
    {
      icon: Users,
      title: 'Smart Coaching',
      desc: 'A recommendation engine that surfaces coaching and scorecards from live performance and routes them.',
    },
    {
      icon: Plug,
      title: 'Connect Everything',
      desc: 'Pre-built connectors for ServiceTitan, HubSpot, Google Ads, QuickBooks, Angi, or push via REST.',
    },
  ];

  return (
    <section className="py-12 md:py-24 px-6" style={sectionStyle()}>
      <div className="max-w-6xl mx-auto">
        <div className="text-center mb-16">
          <h2 className="text-3xl md:text-4xl font-black mb-4">
            From dashboards to decisions
          </h2>
          <p className="text-white/60 text-lg max-w-2xl mx-auto">
            Most tools show you what happened. Command Center forecasts what&apos;s next, sets
            the goals to get there, and routes the follow-ups.
          </p>
        </div>
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {features.map((f) => (
            <div
              key={f.title}
              className="p-6 rounded-2xl border border-white/10 hover:border-white/20 transition-colors"
              style={{ background: COLORS.cardBg }}
            >
              <div className="mb-4" style={{ color: COLORS.blue }}>
                <f.icon size={32} strokeWidth={1.5} />
              </div>
              <h3 className="font-bold text-base mb-2">{f.title}</h3>
              <p className="text-sm text-white/60 leading-relaxed">{f.desc}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Target Audience Section ───
function AudienceSection({ onSeeHow }: { onSeeHow: (audience: 'single' | 'multi' | 'enterprise') => void }) {
  const audiences = [
    {
      type: 'single' as const,
      label: 'For owner-operators',
      title: 'Single-location contractor',
      desc: "You're wearing every hat. Command Center pulls your CRM, ads and books together so you can see what's working this week, without a data team.",
    },
    {
      type: 'multi' as const,
      label: 'For regional operators',
      title: 'Multi-location / regional',
      desc: 'Stop normalizing spreadsheets across branches. Rank markets by close rate, CAC and margin, and see exactly which location to coach next.',
    },
    {
      type: 'enterprise' as const,
      label: 'For platforms & portfolios',
      title: 'Enterprise & PE-backed',
      desc: 'Roll up every operating company, enforce a single KPI taxonomy, and give each brand its own portal, with SSO, custom connectors and an SLA.',
    },
  ];

  return (
    <section className="py-12 md:py-24 px-6" style={sectionStyle({ background: 'rgba(255,255,255,0.02)' })}>
      <div className="max-w-6xl mx-auto">
        <div className="text-center mb-12">
          <h2 className="text-3xl md:text-4xl font-black mb-4">
            Built for how you operate
          </h2>
          <p className="text-white/60 text-lg">
            From a single crew to a PE-backed platform.
          </p>
        </div>
        <div className="grid md:grid-cols-3 gap-6">
          {audiences.map((a) => (
            <div
              key={a.title}
              className="h-full p-6 rounded-2xl border border-white/10 hover:border-white/30 transition-colors cursor-pointer"
              style={{ background: COLORS.cardBg }}
              onClick={() => onSeeHow(a.type)}
            >
              <div
                className="text-xs font-semibold uppercase tracking-wider mb-2"
                style={{ color: COLORS.blue }}
              >
                {a.label}
              </div>
              <h3 className="font-bold text-lg mb-2">{a.title}</h3>
              <p className="text-sm text-white/60 leading-relaxed mb-4">{a.desc}</p>
              <span
                className="text-sm font-semibold flex items-center gap-1"
                style={{ color: COLORS.green }}
              >
                See how <ArrowRight size={14} />
              </span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Industries Section ───
function IndustriesSection() {
  const industries = [
    {
      slug: 'home-services',
      label: 'Home Service',
      title: 'HVAC, plumbing & electrical',
      desc: 'Booked-call rate, average ticket and tech utilization tied to one live landing forecast.',
    },
    {
      slug: 'roofing',
      label: 'Roofing',
      title: 'Residential & storm restoration',
      desc: 'Margin per square, backlog burn-down and storm-cycle re-forecasting within 48 hours.',
    },
    {
      slug: 'remodeling',
      label: 'Remodeling',
      title: 'Kitchen, bath & design-build',
      desc: 'Catch project slippage in week 2 and capture every billable change order.',
    },
  ];

  return (
    <section className="py-12 md:py-24 px-6">
      <div className="max-w-6xl mx-auto">
        <div className="text-center mb-12">
          <h2 className="text-3xl md:text-4xl font-black mb-4">Built for your trade</h2>
          <p className="text-white/60 text-lg">
            Industry-specific KPIs, benchmarks and playbooks out of the box.
          </p>
        </div>
        <div className="grid md:grid-cols-3 gap-6">
          {industries.map((ind) => (
            <Link
              key={ind.slug}
              to={`/industries/${ind.slug}`}
              className="block h-full p-6 rounded-2xl border border-white/10 hover:border-white/30 transition-colors"
              style={{ background: COLORS.cardBg }}
            >
              <div
                className="text-xs font-semibold uppercase tracking-wider mb-2"
                style={{ color: COLORS.blue }}
              >
                {ind.label}
              </div>
              <h3 className="font-bold text-lg mb-2">{ind.title}</h3>
              <p className="text-sm text-white/60 leading-relaxed mb-4">{ind.desc}</p>
              <span
                className="text-sm font-semibold flex items-center gap-1"
                style={{ color: COLORS.green }}
              >
                See how <ArrowRight size={14} />
              </span>
            </Link>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Why Section (4 pillars + impact ripples) ───
function WhySection() {
  const pillars = [
    {
      icon: Crown,
      title: 'Sovereignty',
      desc: 'Know what to do, how to do it, and how to grow. A frictionless path across your whole organization so you own every strategic decision, not your tool stack.',
    },
    {
      icon: BookOpen,
      title: 'Faith & Stewardship',
      desc: 'Conviction in the journey, proof of work over noise. We steward your data, your team, and your trust, steering every decision toward true north.',
    },
    {
      icon: Lightbulb,
      title: 'Truth & Clarity',
      desc: 'Signal over noise. We cut through the chaos and give you data you can actually see and act on, so you never confuse a tool problem for a people problem again.',
    },
    {
      icon: Landmark,
      title: 'Legacy',
      desc: "You're not just building a quarter. You're building a team, a livelihood, a standard for the trades. We build for the long arc: the legacy you're working to leave.",
    },
  ];

  const ripples = [
    {
      label: 'Owners & operators',
      desc: 'Full strategic clarity. Know the number, own the decision, build the legacy you set out to build.',
    },
    {
      label: 'Your team',
      desc: "Everyone knows what 'good' looks like. Goals cascade to every rep. No one's guessing. Accountability becomes a gift, not a threat.",
    },
    {
      label: 'Partners & trade allies',
      desc: 'Clear performance data builds trust. Referrals and co-marketing decisions are made on signal, not gut.',
    },
    {
      label: 'Your customers',
      desc: 'A well-run shop delivers better installations, faster follow-up, and a homeowner experience worth a five-star review.',
    },
    {
      label: 'Your community',
      desc: 'Every thriving contractor means local jobs, stronger livelihoods, and real economic growth in the neighborhoods you serve.',
    },
    {
      label: 'The industry',
      desc: 'When great operators run tight, it raises the bar for the entire trades. Sovereignty at scale changes what the industry looks like.',
    },
  ];

  return (
    <section id="why" className="relative overflow-hidden py-12 md:py-24 px-6" style={sectionStyle()}>
      <div
        className="absolute inset-0 opacity-[0.12]"
        style={{
          background:
            'radial-gradient(ellipse at 80% 0%, #00AECB 0%, transparent 55%), radial-gradient(ellipse at 10% 100%, #00A846 0%, transparent 55%)',
        }}
      />
      <div className="relative max-w-5xl mx-auto">
        <div className="text-center max-w-3xl mx-auto mb-16">
          <div style={badgeStyle(COLORS.blue, 'transparent')}>Our Why</div>
          <h2 className="text-3xl md:text-5xl font-black leading-tight mb-6 mt-6">
            Built for your <span style={{ color: COLORS.green }}>sovereignty</span>.
          </h2>
          <p className="text-lg text-white/70 leading-relaxed">
            Every company, whether a single crew or a national platform, is on its own hero&apos;s
            journey, fighting toward something bigger. Sovereignty means knowing what to do, how
            to do it, and how to grow: a seamless, frictionless path across your whole
            organization. Not your tool stack making the calls. You.
          </p>
        </div>

        {/* 4 pillars */}
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5 mb-16">
          {pillars.map((p) => (
            <div
              key={p.title}
              className="p-7 rounded-2xl border border-white/10 hover:border-white/25 transition-colors"
              style={{ background: COLORS.cardBg }}
            >
              <div className="text-3xl mb-4" style={{ color: COLORS.blue }}>
                <p.icon size={28} strokeWidth={1.5} />
              </div>
              <h3 className="font-bold text-base mb-2" style={{ color: COLORS.blue }}>
                {p.title}
              </h3>
              <p className="text-sm text-white/60 leading-relaxed">{p.desc}</p>
            </div>
          ))}
        </div>

        {/* Impact ripples */}
        <div
          className="rounded-2xl border border-white/10 overflow-hidden"
          style={{ background: 'rgba(255,255,255,0.03)' }}
        >
          <div className="px-8 py-7 border-b border-white/10">
            <h3 className="text-xl md:text-2xl font-black mb-2">
              Sovereignty isn&apos;t just for the CEO.
            </h3>
            <p className="text-white/60 text-sm leading-relaxed max-w-2xl">
              When one company runs with clarity and conviction, the effects ripple outward,
              through teams, partners, customers, communities, and the entire industry. This is
              the legacy we&apos;re building together.
            </p>
          </div>
          <div className="divide-y divide-white/5">
            {ripples.map((r) => (
              <div key={r.label} className="flex flex-col sm:flex-row sm:items-start gap-2 sm:gap-6 px-8 py-5">
                <div
                  className="shrink-0 sm:w-44 text-xs font-bold uppercase tracking-wider pt-0.5"
                  style={{ color: COLORS.green }}
                >
                  {r.label}
                </div>
                <p className="text-sm text-white/65 leading-relaxed">{r.desc}</p>
              </div>
            ))}
          </div>
        </div>

        <p className="text-center text-sm font-semibold uppercase tracking-widest text-white/55 mt-12">
          Sovereignty · Faith &amp; Stewardship · Truth &amp; Clarity · Legacy · steering the
          path to true north
        </p>
      </div>
    </section>
  );
}

// ─── Before / After Transformation ───
function TransformationSection() {
  const beforeItems = [
    { icon: BarChart3, text: 'Numbers live in five tabs and a whiteboard' },
    { icon: Zap, text: "You find out you missed the month after it's over" },
     { icon: Compass, text: "Can't tell a market problem from a rep problem" },
    { icon: TrendingUp, text: 'Monthly review takes two days of prep' },
    { icon: Plug, text: 'Every acquisition has different systems' },
    { icon: Target, text: "Goals don't cascade past the GM" },
  ];

  const afterItems = [
    { icon: Compass, text: 'One source of truth across every tool and market' },
    { icon: TrendingUp, text: 'Live run-rate flags a gap six weeks before month-end' },
    { icon: Target, text: 'Root-cause tree tells your GMs exactly what to fix' },
    { icon: Zap, text: 'Monthly review collapses from two days to two hours' },
    { icon: Plug, text: 'Every acquisition connects to one standard scorecard' },
    { icon: Award, text: 'Cascading goals reach every rep, auto-calculated' },
  ];

  const ListItem = ({ icon: Icon, text, color }: { icon: any; text: string; color: string }) => (
    <li className="flex items-start gap-3 px-6 py-4">
      <span className="text-lg shrink-0 mt-0.5" style={{ color }}>
        <Icon size={20} strokeWidth={2} />
      </span>
      <span className="text-sm leading-relaxed" style={{ color: 'rgba(255,255,255,0.70)' }}>{text}</span>
    </li>
  );

  return (
    <section className="py-12 md:py-24 px-6" style={sectionStyle({ background: 'rgba(255,255,255,0.02)' })}>
      <div className="max-w-5xl mx-auto">
        <div className="text-center mb-14">
          <div style={badgeStyle(COLORS.green, 'transparent')}>The Journey</div>
          <h2 className="text-3xl md:text-4xl font-black mb-4 mt-6">
            From noise to sovereignty.
          </h2>
          <p className="text-white/60 text-lg max-w-2xl mx-auto">
            Every operator we work with starts in the same place. Here&apos;s the transformation.
          </p>
        </div>

        <div className="grid md:grid-cols-2 gap-6 items-start">
          {/* Before */}
          <div
            className="rounded-2xl border overflow-hidden"
            style={{ borderColor: 'rgba(255,77,77,0.25)', background: 'rgba(255,77,77,0.04)' }}
          >
            <div
              className="px-6 py-4 flex items-center gap-3 border-b"
              style={{ borderColor: 'rgba(255,77,77,0.15)', background: 'rgba(255,77,77,0.08)' }}
            >
              <div
                className="w-2.5 h-2.5 rounded-full"
                style={{ background: COLORS.red }}
              />
              <span
                className="font-black text-sm uppercase tracking-wider"
                style={{ color: COLORS.red }}
              >
                The noise
              </span>
            </div>
            <ul className="divide-y divide-[rgba(255,77,77,0.08)]">
              {beforeItems.map((item, i) => (
                <ListItem key={i} icon={item.icon} text={item.text} color={COLORS.red} />
              ))}
            </ul>
          </div>

          {/* After */}
          <div
            className="rounded-2xl border overflow-hidden"
            style={{ borderColor: `${COLORS.green}40`, background: `${COLORS.green}08` }}
          >
            <div
              className="px-6 py-4 flex items-center gap-3 border-b"
              style={{ borderColor: `${COLORS.green}25`, background: `${COLORS.green}12` }}
            >
              <div
                className="w-2.5 h-2.5 rounded-full"
                style={{ background: COLORS.green }}
              />
              <span
                className="font-black text-sm uppercase tracking-wider"
                style={{ color: COLORS.green }}
              >
                Sovereignty
              </span>
              <span
                className="ml-auto text-xs font-semibold px-2 py-0.5 rounded-full"
                style={{ background: `${COLORS.green}20`, color: COLORS.green }}
              >
                Your destination
              </span>
            </div>
            <ul className="divide-y divide-[#00A84610]">
              {afterItems.map((item, i) => (
                <ListItem key={i} icon={item.icon} text={item.text} color={COLORS.green} />
              ))}
            </ul>
          </div>
        </div>

        {/* Bridge */}
        <div className="hidden md:flex items-center justify-center mt-8 gap-4">
          <div
            className="h-px flex-1"
            style={{ background: `linear-gradient(to right, rgba(255,77,77,0.3), ${COLORS.green}60)` }}
          />
          <div
            className="px-5 py-2.5 rounded-full text-xs font-bold border shrink-0"
            style={{ borderColor: `${COLORS.green}40`, color: COLORS.green, background: `${COLORS.green}10` }}
          >
            Command Center is the bridge →
          </div>
          <div
            className="h-px flex-1"
            style={{ background: `linear-gradient(to right, ${COLORS.green}60, rgba(0,168,70,0.1))` }}
          />
        </div>

        <div className="mt-10 text-center">
          <Link
            to="/auth/signup"
            className="px-8 py-3.5 rounded-xl text-base font-bold shadow-lg hover:opacity-90 transition-opacity inline-block"
            style={{ background: COLORS.green }}
          >
            Start your 7-day free trial
          </Link>
        </div>
      </div>
    </section>
  );
}

// ─── Customer Stories / Testimonials ───
function StoriesSection() {
  const stories = [
    {
      badge: '$480K gap closed',
      quote:
        'Command Center forecasts our landing number in real time. We caught a $480K revenue gap six weeks early and closed it.',
      name: 'Marcus Hale',
      role: 'VP of Operations, Summit Exteriors',
      initials: 'MH',
    },
    {
      badge: '+23% booked-job rate',
      quote:
        "The cascading goals changed how our crews think. Every rep sees their own target tied to the company number. Booked-job rate is up 23% since rollout and nobody's guessing what 'good' looks like anymore.",
      name: 'Priya Nair',
      role: 'Director of Sales, Evergreen Home Services',
      initials: 'PN',
    },
    {
      badge: '2 days → 2 hours',
      quote:
        'As a PE-backed platform across nine markets, we needed one source of truth. The root-cause tree tells our GMs exactly which driver to fix. We cut our monthly review from two days to two hours.',
      name: 'David Okonkwo',
      role: 'CFO, Atlas Home Brands',
      initials: 'DO',
    },
  ];

  return (
    <section id="stories" className="py-12 md:py-24 px-6" style={{ background: 'rgba(255,255,255,0.02)' }}>
      <div className="max-w-5xl mx-auto">
        <div className="text-center mb-14">
          <p className="text-center text-xs font-semibold uppercase tracking-widest text-white/40 mb-8">
            Trusted by operators across the country
          </p>
          <h2 className="text-3xl md:text-4xl font-black mb-4">Customer Stories</h2>
          <p className="text-white/60 text-lg max-w-2xl mx-auto">
            Real numbers from operators who made the switch.
          </p>
        </div>
        <div className="grid md:grid-cols-3 gap-6">
          {stories.map((s) => (
            <figure
              key={s.name}
              className="flex flex-col h-full p-7 rounded-2xl border border-white/10 hover:border-white/25 transition-colors"
              style={{ background: COLORS.cardBg }}
            >
              <div
                className="inline-flex self-start items-center px-3 py-1 rounded-full text-xs font-bold mb-5"
                style={{ background: `${COLORS.green}1f`, color: COLORS.green }}
              >
                {s.badge}
              </div>
              <blockquote
                className="text-sm text-white/75 leading-relaxed flex-1 mb-6"
              >
                &ldquo;{s.quote}&rdquo;
              </blockquote>
              <figcaption className="pt-5 border-t border-white/10">
                <div className="flex items-center gap-3">
                  <div
                    className="w-10 h-10 rounded-full flex items-center justify-center text-xs font-bold shrink-0"
                    style={{
                      background: `linear-gradient(135deg, ${COLORS.blue}, ${COLORS.green})`,
                      color: '#001018',
                    }}
                  >
                    {s.initials}
                  </div>
                  <div>
                    <div className="text-sm font-semibold">{s.name}</div>
                    <div className="text-xs text-white/50">{s.role}</div>
                  </div>
                </div>
              </figcaption>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Pricing Section ───
function PricingSection() {
  const plans = [
    {
      id: 'launch',
      name: 'Launch',
      price: '$299',
      period: '/mo',
      desc: 'Get your command center stood up and connected.',
      summary: '1 market · 5 seats',
      summary2: '3 integrations · 5 GB',
      features: [
        '1 market',
        'Up to 5 seats',
        '3 integrations',
        'Strategic Intelligence dashboards',
        '5 GB data storage',
        'Email support',
      ],
      cta: 'Start 7-day trial',
      ctaBg: 'rgba(255,255,255,0.1)',
      ctaColor: '#fff',
      nameColor: COLORS.blue,
      popular: false,
    },
    {
      id: 'growth',
      name: 'Growth',
      price: '$899',
      period: '/mo',
      desc: 'Forecast the quarter and cascade the number to every rep.',
      summary: '5 markets · 25 seats',
      summary2: '10 integrations · 50 GB',
      features: [
        'Up to 5 markets',
        'Up to 25 seats',
        '10 integrations',
        'Forecasting & cascading goals',
        'Field Companion mobile app',
        '50 GB data storage',
      ],
      cta: 'Start 7-day trial',
      ctaBg: COLORS.green,
      ctaColor: '#000',
      nameColor: COLORS.green,
      popular: true,
    },
    {
      id: 'command',
      name: 'Command',
      price: '$2,499',
      period: '/mo',
      desc: 'Let the platform tell each leader exactly what to fix next.',
      summary: '25 markets · 100 seats',
      summary2: '50 integrations · 250 GB',
      features: [
        'Up to 25 markets',
        'Up to 100 seats',
        '50 integrations',
        'AI Intervention engine',
        'Custom connectors',
        '250 GB data storage',
      ],
      cta: 'Start 7-day trial',
      ctaBg: 'rgba(255,255,255,0.1)',
      ctaColor: '#fff',
      nameColor: COLORS.blue,
      popular: false,
    },
    {
      id: 'enterprise',
      name: 'Enterprise',
      price: 'Custom',
      period: '',
      desc: 'Unlimited scale, white-label, SSO and an SLA.',
      summary: 'Unlimited markets · Unlimited seats',
      summary2: 'Unlimited integrations · Unlimited GB',
      features: [
        'Unlimited markets, seats & integrations',
        'White-label branding',
        'SSO / SAML',
        'Unlimited data storage',
        'Custom connectors',
        'Dedicated CSM & SLA',
      ],
      cta: 'Contact sales',
      ctaBg: 'rgba(255,255,255,0.1)',
      ctaColor: '#fff',
      nameColor: COLORS.blue,
      popular: false,
    },
  ];

  return (
    <section id="pricing" className="py-12 md:py-24 px-6" style={sectionStyle({ background: 'rgba(255,255,255,0.02)' })}>
      <div className="max-w-6xl mx-auto">
        <div className="text-center mb-16">
          <h2 className="text-3xl md:text-4xl font-black mb-4">
            Pricing that scales with you
          </h2>
          <p className="text-white/60 text-lg">
            Start with a 7-day free trial on Launch. Upgrade as you add markets, seats and
            integrations.
          </p>
        </div>
        <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-5">
          {plans.map((plan) => (
            <div
              key={plan.name}
              className="relative p-6 rounded-2xl border flex flex-col"
              style={{
                borderColor: plan.popular ? COLORS.green : COLORS.cardBorder,
                background: plan.popular ? `${COLORS.green}12` : COLORS.cardBg,
              }}
            >
              {plan.popular && (
                <div
                  className="absolute -top-3 left-1/2 -translate-x-1/2 px-3 py-1 rounded-full text-xs font-bold"
                  style={{ background: COLORS.green, color: '#000' }}
                >
                  Most Popular
                </div>
              )}
              <h3 className="font-black text-lg mb-1" style={{ color: plan.nameColor }}>
                {plan.name}
              </h3>
              <div className="mb-1">
                <span className="text-2xl font-bold">{plan.price}</span>
                {plan.period && <span className="text-sm text-white/40">{plan.period}</span>}
              </div>
              <p className="text-xs text-white/50 mb-4 min-h-[2.5rem]">{plan.desc}</p>
              <div className="text-[11px] text-white/40 mb-4 space-y-0.5">
                <div>{plan.summary}</div>
                <div>{plan.summary2}</div>
              </div>
              <ul className="space-y-2 flex-1 mb-6">
                {plan.features.map((f) => (
                  <li key={f} className="flex items-start gap-2 text-xs">
                    <span style={{ color: COLORS.green }}>✓</span>
                    <span className="text-white/70">{f}</span>
                  </li>
                ))}
              </ul>
              <Link
                to={`/auth/signup${plan.id !== 'enterprise' ? `?plan=${plan.id}` : ''}`}
                className="w-full py-2.5 rounded-lg text-sm font-semibold text-center transition-all hover:opacity-90 block min-h-[44px]"
                style={{ background: plan.ctaBg, color: plan.ctaColor }}
              >
                {plan.cta}
              </Link>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─── Demo / CTA Section ───
function DemoSection() {
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [formError, setFormError] = useState('');
  const [formState, setFormState] = useState({
    name: '', email: '', company: '', phone: '', message: ''
  });

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormError('');
    setSubmitting(true);
    try {
      const res = await fetch('/api/leads/demo-request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formState),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || 'Submission failed');
      }
      setSubmitted(true);
    } catch (err: any) {
      setFormError(err.message || 'Something went wrong');
    } finally {
      setSubmitting(false);
    }
  };

  const handleChange = (field: string) => (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => setFormState(prev => ({ ...prev, [field]: e.target.value }));

  return (
    <section id="demo" className="py-12 md:py-24 px-6">
      <div className="max-w-5xl mx-auto grid md:grid-cols-2 gap-10 items-stretch">
        <div className="flex flex-col justify-center">
          <div style={badgeStyle(COLORS.lime, `${COLORS.lime}12`)}>
            <span
              className="w-1.5 h-1.5 rounded-full bg-current"
              style={{ animation: 'pulse 2s infinite' }}
            />
            Booking walkthroughs now
          </div>
          <h2 className="text-3xl md:text-4xl font-black mb-4">
            See it on your data
          </h2>
          <p className="text-white/70 text-lg leading-relaxed mb-6">
            Book a 30-minute walkthrough. We&apos;ll connect your tools and show you the
            forecast, the gap, and the plan to close it, live on your numbers.
          </p>
          <ul className="space-y-2.5 text-sm text-white/65 mb-7">
            {[
              'Personalized to your markets',
              'No prep required',
              'Bring your toughest question',
            ].map((item) => (
              <li key={item} className="flex items-center gap-2.5">
                <span
                  className="flex items-center justify-center w-5 h-5 rounded-full text-[10px] font-black shrink-0"
                  style={{ background: `${COLORS.lime}22`, color: COLORS.lime }}
                >
                  ✓
                </span>
                {item}
              </li>
            ))}
          </ul>

          <figure
            className="rounded-2xl border border-white/10 p-5"
            style={{ background: 'rgba(255,255,255,0.03)' }}
          >
            <blockquote className="text-sm text-white/75 leading-relaxed mb-3">
              &ldquo;We caught a $480K revenue gap six weeks early and closed it. The walkthrough
              paid for the year in one call.&rdquo;
            </blockquote>
            <figcaption className="flex items-center gap-2.5">
              <div
                className="w-8 h-8 rounded-full flex items-center justify-center text-[10px] font-bold shrink-0"
                style={{
                  background: `linear-gradient(135deg, ${COLORS.blue}, ${COLORS.green})`,
                  color: '#001018',
                }}
              >
                MH
              </div>
              <div className="text-xs text-white/55">
                Marcus Hale, VP Operations, Summit Exteriors
              </div>
            </figcaption>
          </figure>
        </div>

        {/* Demo form */}
        <div
          className="rounded-2xl border border-white/10 p-6 md:p-7"
          style={{ background: 'rgba(255,255,255,0.04)' }}
        >
          {submitted ? (
            <div className="flex flex-col items-center justify-center py-10 text-center">
              <div
                className="w-16 h-16 rounded-full flex items-center justify-center mb-4"
                style={{ background: `${COLORS.green}22` }}
              >
                <Check size={32} style={{ color: COLORS.green }} />
              </div>
              <h3 className="font-black text-xl mb-2">Request submitted!</h3>
              <p className="text-sm text-white/60">
                A specialist will reach out within one business day.
              </p>
            </div>
          ) : (
            <>
              <h3 className="font-black text-lg mb-1">Request your walkthrough</h3>
              <p className="text-sm text-white/50 mb-5">
                A specialist reaches out within one business day.
              </p>
              {formError && (
                <div className="mb-3 p-3 rounded-lg text-sm text-red-400 bg-red-500/10 border border-red-500/20">
                  {formError}
                </div>
              )}
              <form
                className="flex flex-col gap-3 text-left"
                onSubmit={handleSubmit}
              >
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <input
                    required
                    className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-3 text-sm text-white outline-none focus:border-white/30 placeholder:text-white/25"
                    placeholder="Full name"
                    value={formState.name}
                    onChange={handleChange('name')}
                  />
                  <input
                    type="email"
                    required
                    className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-3 text-sm text-white outline-none focus:border-white/30 placeholder:text-white/25"
                    placeholder="Work email"
                    value={formState.email}
                    onChange={handleChange('email')}
                  />
                  <input
                    className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-3 text-sm text-white outline-none focus:border-white/30 placeholder:text-white/25"
                    placeholder="Company"
                    value={formState.company}
                    onChange={handleChange('company')}
                  />
                  <input
                    className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-3 text-sm text-white outline-none focus:border-white/30 placeholder:text-white/25"
                    placeholder="Phone (optional)"
                    value={formState.phone}
                    onChange={handleChange('phone')}
                  />
                </div>
                <textarea
                  className="w-full rounded-lg border border-white/10 bg-white/5 px-3 py-3 text-sm text-white outline-none focus:border-white/30 placeholder:text-white/25 resize-none"
                  rows={3}
                  placeholder="What would you like to see? (optional)"
                  value={formState.message}
                  onChange={handleChange('message')}
                />
                <button
                  type="submit"
                  disabled={submitting}
                  className="w-full py-3 rounded-xl font-bold text-sm transition-all hover:opacity-90 disabled:opacity-50"
                  style={{ background: COLORS.green }}
                >
                  {submitting ? 'Sending…' : 'Request a demo'}
                </button>
              </form>
            </>
          )}
        </div>
      </div>
    </section>
  );
}

// ─── Final CTA ───
function FinalCTA() {
  return (
    <section className="py-12 md:py-24 px-6" style={sectionStyle({ background: 'rgba(255,255,255,0.02)' })}>
      <div className="max-w-3xl mx-auto text-center p-8 md:p-12 rounded-3xl border border-white/10" style={{ background: 'linear-gradient(135deg, #00305780, #00AECB20)' }}>
        <p className="text-xs font-semibold uppercase tracking-widest mb-4" style={{ color: COLORS.blue }}>
          Signal Over Noise · True North for the Trades
        </p>
        <h2 className="text-3xl md:text-4xl font-black mb-4">
          Ready to command your number?
        </h2>
        <p className="text-white/70 text-lg mb-8">
          Start free today. No card, no implementation project. Sovereignty starts here.
        </p>
        <Link
          to="/auth/signup"
          className="px-10 py-4 rounded-xl text-base font-bold hover:opacity-90 transition-opacity inline-block"
          style={{ background: COLORS.green }}
        >
          Start 7-day free trial
        </Link>
      </div>
    </section>
  );
}

// ─── Footer ───
function Footer() {
  return (
    <footer className="border-t border-white/10 py-8 px-6">
      <div className="max-w-6xl mx-auto flex flex-wrap items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <div
            className="w-6 h-6 rounded-md flex items-center justify-center font-black text-[10px]"
            style={{ background: COLORS.green }}
          >
            CC
          </div>
          <div>
            <span className="text-sm font-semibold">Command Center</span>
            <span className="hidden sm:inline text-xs text-white/55 ml-2">
              · Signal Over Noise · True North for the Trades
            </span>
          </div>
        </div>
        <div className="flex gap-6 text-sm text-white/60">
          <a href="#pricing" className="hover:text-white/70 transition-colors py-2 inline-block">
            Pricing
          </a>
          <a href="#why" className="hover:text-white/70 transition-colors py-2 inline-block">
            Docs
          </a>
          <Link to="/auth/signup" className="hover:text-white/70 transition-colors py-2 inline-block">
            Start free
          </Link>
          <Link to="/auth/login" className="hover:text-white/70 transition-colors py-2 inline-block">
            Log in
          </Link>
        </div>
        <p className="text-xs text-white/55">© 2026 Command Center. All rights reserved.</p>
      </div>
    </footer>
  );
}

// ─── Main Landing Page ───
export function LandingPage() {
  const [activeModal, setActiveModal] = useState<'single' | 'multi' | 'enterprise' | null>(null);

  return (
    <div className="min-h-screen text-white" style={{ background: COLORS.bg }}>
      <style>{`
        html { scroll-behavior: smooth; }
        @keyframes pulse {
          0%, 100% { opacity: 1; }
          50% { opacity: 0.5; }
        }
      `}</style>
      <Navigation />
      <HeroSection />
      <IntegrationsBar />
      <ManifestoSection />
      <FeaturesSection />
      <AudienceSection onSeeHow={setActiveModal} />
      <IndustriesSection />
      <WhySection />
      <TransformationSection />
      <StoriesSection />
      <PricingSection />
      <DemoSection />
      <FinalCTA />
      <Footer />

      {/* Feature walkthrough modals */}
      {activeModal && (
        <FeatureModal
          audience={activeModal}
          onClose={() => setActiveModal(null)}
        />
      )}
    </div>
  );
}
