import { Link, useParams, Navigate } from 'react-router-dom';
import {
  ArrowRight, ArrowLeft, Check, TrendingUp, Target, BarChart3,
  Zap, DollarSign, Users, Gauge,
} from 'lucide-react';
import {
  ResponsiveContainer, AreaChart, Area, XAxis, YAxis, Tooltip, CartesianGrid,
} from 'recharts';

// ─── Brand colors (mirrors LandingPage) ───
const COLORS = {
  bg: '#0a0f1a',
  cardBg: 'rgba(255,255,255,0.04)',
  green: '#22c55e',
  blue: '#3b82f6',
  amber: '#f59e0b',
};

interface IndustryMetric {
  label: string;
  value: string;
  sub: string;
  icon: React.ElementType;
}

interface IndustryUseCase {
  title: string;
  desc: string;
}

interface IndustryData {
  slug: string;
  name: string;
  tagline: string;
  headline: string;
  subhead: string;
  metrics: IndustryMetric[];
  useCases: IndustryUseCase[];
  chartLabel: string;
  chart: { month: string; baseline: number; withCC: number }[];
  checklist: string[];
}

const INDUSTRIES: Record<string, IndustryData> = {
  'home-services': {
    slug: 'home-services',
    name: 'Home Services',
    tagline: 'HVAC · Plumbing · Electrical · Landscaping',
    headline: 'Run every truck like a profit center',
    subhead:
      'Home service companies live and die by booked-call rate, average ticket, and technician utilization. Command Center pulls your CRM, ads, and books into one forecast so you know this week — not next quarter — whether you will hit your number.',
    metrics: [
      { label: 'Booked-call rate', value: '+18%', sub: 'avg. lift after cascading goals rollout', icon: Target },
      { label: 'Average ticket', value: '+$212', sub: 'from real-time upsell coaching signals', icon: DollarSign },
      { label: 'Tech utilization', value: '87%', sub: 'vs. 71% industry median', icon: Gauge },
      { label: 'Forecast accuracy', value: '±4%', sub: 'weekly revenue landing forecast', icon: TrendingUp },
    ],
    useCases: [
      { title: 'Dispatch-to-revenue visibility', desc: 'See how today\u2019s call board translates into this month\u2019s landing number, by trade and by tech.' },
      { title: 'Seasonal demand forecasting', desc: 'Model shoulder-season dips before they hit cash flow and shift ad spend into the right zip codes early.' },
      { title: 'Membership program tracking', desc: 'Track maintenance agreement attach rate as a cascading goal for every CSR and technician.' },
    ],
    chartLabel: 'Monthly revenue vs. baseline ($K)',
    chart: [
      { month: 'Jan', baseline: 310, withCC: 310 },
      { month: 'Feb', baseline: 295, withCC: 318 },
      { month: 'Mar', baseline: 330, withCC: 365 },
      { month: 'Apr', baseline: 355, withCC: 410 },
      { month: 'May', baseline: 372, withCC: 448 },
      { month: 'Jun', baseline: 390, withCC: 486 },
    ],
    checklist: [
      'Connect ServiceTitan, Housecall Pro, or your CRM in minutes',
      'Booked-call rate and average ticket as live KPIs',
      'Per-technician scorecards tied to the company forecast',
      'Ad spend recommendations by service line and zip',
    ],
  },
  roofing: {
    slug: 'roofing',
    name: 'Roofing',
    tagline: 'Residential · Commercial · Storm restoration',
    headline: 'From lead to shingle, know your landing number',
    subhead:
      'Roofing margins swing with material costs, crew availability, and storm cycles. Command Center forecasts your close rate, backlog burn-down, and gross margin per square — so you can commit to jobs you can actually staff and price.',
    metrics: [
      { label: 'Close rate', value: '+9pts', sub: 'with rep-level cascading targets', icon: Target },
      { label: 'Gross margin / square', value: '+6.4%', sub: 'from material cost drift alerts', icon: DollarSign },
      { label: 'Backlog visibility', value: '10 wks', sub: 'forward crew-loading forecast', icon: BarChart3 },
      { label: 'Storm-surge response', value: '48 hrs', sub: 'to re-forecast after weather events', icon: Zap },
    ],
    useCases: [
      { title: 'Storm-cycle revenue modeling', desc: 'Re-forecast pipeline within hours of a hail event and rank markets by expected insurance claim volume.' },
      { title: 'Material cost drift alerts', desc: 'Catch shingle and underlayment price creep before it eats the margin you quoted three weeks ago.' },
      { title: 'Crew capacity planning', desc: 'See backlog burn-down against crew availability so sales never commits to a date production can\u2019t hit.' },
    ],
    chartLabel: 'Quarterly gross margin trend (%)',
    chart: [
      { month: 'Q1 \u201924', baseline: 24, withCC: 24 },
      { month: 'Q2 \u201924', baseline: 23, withCC: 26 },
      { month: 'Q3 \u201924', baseline: 25, withCC: 29 },
      { month: 'Q4 \u201924', baseline: 24, withCC: 30 },
      { month: 'Q1 \u201925', baseline: 23, withCC: 31 },
      { month: 'Q2 \u201925', baseline: 24, withCC: 32 },
    ],
    checklist: [
      'Insurance vs. retail job mix tracked separately',
      'Margin-per-square as a first-class KPI',
      'Supplier price drift monitoring',
      'Crew-loading forecast tied to sales pipeline',
    ],
  },
  remodeling: {
    slug: 'remodeling',
    name: 'Remodeling',
    tagline: 'Kitchen & bath · Whole-home · Design-build',
    headline: 'Long projects, short feedback loops',
    subhead:
      'Remodelers get surprised at the end of 12-week projects. Command Center tracks slippage, change-order capture, and design-to-build conversion continuously — so a project that\u2019s drifting off budget shows up in week 2, not week 11.',
    metrics: [
      { label: 'Change-order capture', value: '+31%', sub: 'billable scope changes actually invoiced', icon: DollarSign },
      { label: 'Slippage detection', value: 'Wk 2', sub: 'vs. end-of-project surprises', icon: Gauge },
      { label: 'Design→build conversion', value: '+12pts', sub: 'with pipeline-stage forecasting', icon: Target },
      { label: 'Referral pipeline', value: '38%', sub: 'of new revenue tracked to past clients', icon: Users },
    ],
    useCases: [
      { title: 'Project margin tracking', desc: 'Live budget-vs-actual per project, rolled up to a company landing number your bookkeeper doesn\u2019t have to rebuild.' },
      { title: 'Change-order discipline', desc: 'Every scope change gets a dollar value and a status — no more free work discovered at final invoice.' },
      { title: 'Design-phase pipeline', desc: 'Forecast build revenue from design contracts signed today, 4\u20136 months ahead of the crews.' },
    ],
    chartLabel: 'Project margin: quoted vs. delivered (%)',
    chart: [
      { month: 'Jan', baseline: 18, withCC: 18 },
      { month: 'Feb', baseline: 16, withCC: 19 },
      { month: 'Mar', baseline: 17, withCC: 21 },
      { month: 'Apr', baseline: 15, withCC: 22 },
      { month: 'May', baseline: 17, withCC: 24 },
      { month: 'Jun', baseline: 16, withCC: 25 },
    ],
    checklist: [
      'Budget-vs-actual per project, updated continuously',
      'Change-order pipeline with capture-rate KPI',
      'Design-to-build conversion forecasting',
      'Client referral revenue attribution',
    ],
  },
};

export function IndustryPage() {
  const { slug } = useParams<{ slug: string }>();
  const data = slug ? INDUSTRIES[slug] : undefined;

  if (!data) {
    return <Navigate to="/" replace />;
  }

  return (
    <div className="min-h-screen text-white" style={{ background: COLORS.bg }}>
      {/* Nav */}
      <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 text-sm tracking-tight">Command Center</span>
          </Link>
          <div className="flex items-center 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] flex items-center"
              style={{ background: COLORS.green }}
            >
              Start free trial
            </Link>
          </div>
        </nav>
      </header>

      {/* Hero */}
      <section className="pt-16 pb-12 px-6">
        <div className="max-w-6xl mx-auto">
          <Link to="/" className="inline-flex items-center gap-1 text-sm text-white/50 hover:text-white transition-colors mb-6">
            <ArrowLeft size={14} /> Back to home
          </Link>
          <div
            className="text-xs font-semibold uppercase tracking-wider mb-3"
            style={{ color: COLORS.blue }}
          >
            {data.tagline}
          </div>
          <h1 className="text-4xl md:text-5xl font-black mb-4 max-w-3xl">{data.headline}</h1>
          <p className="text-lg text-white/60 leading-relaxed max-w-3xl mb-8">{data.subhead}</p>
          <div className="flex flex-wrap gap-3">
            <Link
              to="/auth/signup"
              className="px-6 py-3 rounded-full text-sm font-semibold flex items-center gap-2 transition-all hover:opacity-90"
              style={{ background: COLORS.green }}
            >
              Start free trial <ArrowRight size={16} />
            </Link>
            <Link
              to="/#demo"
              className="px-6 py-3 rounded-full text-sm font-semibold border border-white/20 hover:border-white/40 transition-colors"
            >
              Book a demo
            </Link>
          </div>
        </div>
      </section>

      {/* Metrics */}
      <section className="py-12 px-6" style={{ background: 'rgba(255,255,255,0.02)' }}>
        <div className="max-w-6xl mx-auto grid grid-cols-2 md:grid-cols-4 gap-4">
          {data.metrics.map((m) => {
            const Icon = m.icon;
            return (
              <div
                key={m.label}
                className="p-5 rounded-2xl border border-white/10"
                style={{ background: COLORS.cardBg }}
              >
                <Icon size={18} style={{ color: COLORS.green }} className="mb-3" />
                <div className="text-2xl font-black">{m.value}</div>
                <div className="text-sm font-semibold text-white/80 mt-1">{m.label}</div>
                <div className="text-xs text-white/50 mt-1">{m.sub}</div>
              </div>
            );
          })}
        </div>
      </section>

      {/* Chart + checklist */}
      <section className="py-16 px-6">
        <div className="max-w-6xl mx-auto grid md:grid-cols-2 gap-10 items-center">
          <div>
            <h2 className="text-2xl md:text-3xl font-black mb-3">
              What {data.name.toLowerCase()} operators see
            </h2>
            <p className="text-white/60 mb-6">
              Illustrative example of the operating picture Command Center builds for {data.name.toLowerCase()} companies.
            </p>
            <ul className="space-y-3">
              {data.checklist.map((item) => (
                <li key={item} className="flex items-start gap-3 text-sm text-white/80">
                  <Check size={16} style={{ color: COLORS.green }} className="mt-0.5 shrink-0" />
                  {item}
                </li>
              ))}
            </ul>
          </div>
          <div
            className="p-5 rounded-2xl border border-white/10"
            style={{ background: COLORS.cardBg }}
          >
            <div className="text-sm font-semibold text-white/70 mb-4">{data.chartLabel}</div>
            <div className="h-64">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={data.chart} margin={{ top: 5, right: 5, bottom: 0, left: -20 }}>
                  <defs>
                    <linearGradient id="ccGreen" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="0%" stopColor={COLORS.green} stopOpacity={0.35} />
                      <stop offset="100%" stopColor={COLORS.green} stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid stroke="rgba(255,255,255,0.06)" vertical={false} />
                  <XAxis dataKey="month" tick={{ fill: 'rgba(255,255,255,0.5)', fontSize: 12 }} axisLine={false} tickLine={false} />
                  <YAxis tick={{ fill: 'rgba(255,255,255,0.5)', fontSize: 12 }} axisLine={false} tickLine={false} />
                  <Tooltip
                    contentStyle={{ background: '#111827', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 8 }}
                    labelStyle={{ color: '#fff' }}
                  />
                  <Area type="monotone" dataKey="baseline" name="Baseline" stroke="rgba(255,255,255,0.35)" fill="transparent" strokeDasharray="4 4" />
                  <Area type="monotone" dataKey="withCC" name="With Command Center" stroke={COLORS.green} fill="url(#ccGreen)" strokeWidth={2} />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </div>
        </div>
      </section>

      {/* Use cases */}
      <section className="py-12 px-6" style={{ background: 'rgba(255,255,255,0.02)' }}>
        <div className="max-w-6xl mx-auto">
          <h2 className="text-2xl md:text-3xl font-black mb-8 text-center">
            How {data.name.toLowerCase()} teams use Command Center
          </h2>
          <div className="grid md:grid-cols-3 gap-6">
            {data.useCases.map((uc) => (
              <div
                key={uc.title}
                className="p-6 rounded-2xl border border-white/10"
                style={{ background: COLORS.cardBg }}
              >
                <h3 className="font-bold text-lg mb-2">{uc.title}</h3>
                <p className="text-sm text-white/60 leading-relaxed">{uc.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Other industries */}
      <section className="py-12 px-6">
        <div className="max-w-6xl mx-auto">
          <h3 className="text-lg font-bold mb-4 text-white/70">Also built for</h3>
          <div className="flex flex-wrap gap-3">
            {Object.values(INDUSTRIES)
              .filter((i) => i.slug !== data.slug)
              .map((i) => (
                <Link
                  key={i.slug}
                  to={`/industries/${i.slug}`}
                  className="px-5 py-2.5 rounded-full text-sm font-semibold border border-white/15 hover:border-white/40 transition-colors flex items-center gap-2"
                >
                  {i.name} <ArrowRight size={14} style={{ color: COLORS.green }} />
                </Link>
              ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="py-16 px-6 text-center" style={{ background: 'rgba(34,197,94,0.06)' }}>
        <div className="max-w-3xl mx-auto">
          <h2 className="text-3xl font-black mb-4">See your landing number this week</h2>
          <p className="text-white/60 mb-8">
            Connect your CRM and books, and Command Center builds your first forecast in under an hour.
          </p>
          <Link
            to="/auth/signup"
            className="inline-flex items-center gap-2 px-8 py-3.5 rounded-full font-semibold transition-all hover:opacity-90"
            style={{ background: COLORS.green }}
          >
            Start free trial <ArrowRight size={16} />
          </Link>
        </div>
      </section>

      <footer className="py-8 px-6 border-t border-white/10 text-center text-sm text-white/40">
        © {new Date().getFullYear()} Command Center. All rights reserved.
      </footer>
    </div>
  );
}

export default IndustryPage;
