// Industry Selector, tabbed vertical selector with animated expand
const { useState: useIndState, useEffect: useIndEffect, useRef: useIndRef } = React;

const INDUSTRIES = [
  {
    id: 'medspas',
    icon: '✦',
    name: 'Med Spas',
    tagline: 'Lose $400 every missed call?',
    tag: '// MED SPA',
    color: '#00D9A0',
    pains: [
      'Missed calls during treatments = $400+ per lost appointment',
      'Instagram DMs go dark after hours, leads go cold',
      'No-shows kill daily revenue and staff morale',
    ],
    solutions: [
      'AI receptionist that books 24/7 via call, SMS, and DM',
      'Instagram DM qualifier that pre-screens leads automatically',
      'No-show recovery agent with smart rebooking sequences',
    ],
    outcome: 'Clients see 30–45% reduction in no-shows within 60 days.',
    metric: { value: '+$184K', label: 'recovered annually · 8-room med spa' },
    quote: { text: 'Bookings up 38%. We stopped losing every after-hours lead.', author: 'Owner · 8-treatment-room med spa' },
    cta: 'See Med Spa builds →',
    ctaHref: 'work.html',
  },
  {
    id: 'cpa',
    icon: '◈',
    name: 'CPA Firms',
    tagline: 'Tax season burning out your team?',
    tag: '// CPA & ACCOUNTING',
    color: '#8B5CF6',
    pains: [
      'Manual document review eats 40+ hours per partner per season',
      'Client onboarding is a fragmented mess of email chains',
      'IRS/HMRC notices pile up while staff handle routine queries',
    ],
    solutions: [
      'AI workpaper assistant that flags issues before review',
      'Client onboarding agent, intake to engagement letter, automated',
      'IRS/HMRC notice triage with priority routing and draft responses',
    ],
    outcome: 'Partners report 15+ hours saved weekly during peak season.',
    metric: { value: '15 hrs', label: 'saved per partner per week · peak season' },
    quote: { text: 'Tax season stopped breaking us. Partners actually took weekends off.', author: 'Managing Partner · 4-partner CPA firm' },
    cta: 'See CPA builds →',
    ctaHref: 'work.html',
  },
  {
    id: 'realestate',
    icon: '◎',
    name: 'Real Estate',
    tagline: 'Slow lead response killing deals?',
    tag: '// REAL ESTATE',
    color: '#F59E0B',
    pains: [
      '78% of buyers go with the first agent who responds, yours is asleep',
      'Listing descriptions take 2+ hours per property',
      'Transaction coordinators drown in showing logistics',
    ],
    solutions: [
      'Lead qualification agent, responds in 90 seconds, 24/7',
      'Listing description generator from MLS data + photos',
      'Showing scheduler and TC copilot for closing coordination',
    ],
    outcome: 'Lead response time cut from 4 hours to under 2 minutes.',
    metric: { value: '< 2 min', label: 'lead response · 24/7 · vs 4 hrs before' },
    quote: { text: 'We close the leads competitors never even reply to.', author: 'Team Lead · 18-agent real estate brokerage' },
    cta: 'See Real Estate builds →',
    ctaHref: 'work.html',
  },
  {
    id: 'lawfirms',
    icon: '⬡',
    name: 'Law Firms',
    tagline: 'Intake friction costing you clients?',
    tag: '// LAW FIRMS',
    color: '#00D9A0',
    pains: [
      'New client intake takes days and involves 6+ manual steps',
      'Contract drafting consumes hours a senior associate could bill out',
      'Client status updates require staff to pull files and call back',
    ],
    solutions: [
      'Intake bot with conflict-check integration and e-sign flow',
      'Contract draft assistant, first draft in minutes, not hours',
      'Client status updater via SMS/email, zero staff time',
    ],
    outcome: 'Intake-to-engagement cut from 3 days to 4 hours.',
    metric: { value: '4 hrs', label: 'intake-to-engagement · vs 3 days before' },
    quote: { text: 'Senior associates bill the hours they used to lose to admin.', author: 'Partner · 12-attorney litigation firm' },
    cta: 'See Law Firm builds →',
    ctaHref: 'work.html',
  },
  {
    id: 'retail',
    icon: '◇',
    name: 'Retail & E-com',
    tagline: 'Support volume crushing your margins?',
    tag: '// RETAIL',
    color: '#8B5CF6',
    pains: [
      'Customer support volume scales with revenue, team can\'t keep up',
      'Returns processing eats 3+ staff hours per day',
      'Review response is an afterthought, reputation suffers',
    ],
    solutions: [
      'AI customer support agent handling 80% of tickets autonomously',
      'Returns triage system, policy check, refund initiation, escalation',
      'Review response automation across Google, Yelp, and Trustpilot',
    ],
    outcome: '80% of support tickets resolved without human touch.',
    metric: { value: '80%', label: 'tickets resolved · zero human touch' },
    quote: { text: 'Our support team scaled 4× without hiring a single person.', author: 'Operations · DTC e-com brand · $14M/yr' },
    cta: 'See Retail builds →',
    ctaHref: 'work.html',
  },
];

function IndustrySelector() {
  const [active, setActive] = useIndState('medspas');
  const [revealed, setRevealed] = useIndState(false);
  const sectionRef = useIndRef(null);

  useIndEffect(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) setRevealed(true);
    }, { threshold: 0.15 });
    if (sectionRef.current) obs.observe(sectionRef.current);
    return () => obs.disconnect();
  }, []);

  const activeData = INDUSTRIES.find(i => i.id === active);

  return (
    <section id="industries" ref={sectionRef} style={{
      padding: '120px 0 80px',
      position: 'relative',
      overflow: 'hidden',
    }}>
      {/* Section bg accent */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, bottom: 0,
        background: 'linear-gradient(180deg, transparent 0%, rgba(124,92,255,0.02) 50%, transparent 100%)',
        pointerEvents: 'none',
      }} />

      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 40px' }}>
        {/* Header */}
        <div style={{
          marginBottom: 56,
          opacity: revealed ? 1 : 0,
          transform: revealed ? 'translateY(0)' : 'translateY(24px)',
          transition: 'all 0.6s var(--ease-expo)',
        }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 11,
            color: 'var(--accent-mint-text)', letterSpacing: '0.12em',
            textTransform: 'uppercase', marginBottom: 12,
          }}>// PICK YOUR INDUSTRY</div>
          <h2 style={{
            fontFamily: 'Syne, sans-serif',
            fontSize: 'clamp(28px, 4vw, 52px)',
            fontWeight: 700, letterSpacing: '-0.02em',
            lineHeight: 1.12, color: 'var(--text-primary)',
            maxWidth: 600,
          }}>
            We know your industry.<br />
            <span style={{ color: 'var(--text-secondary)', fontWeight: 500 }}>Not just your workflows.</span>
          </h2>
        </div>

        {/* Tab row */}
        <div style={{
          display: 'flex', gap: 0,
          background: 'var(--bg-secondary)',
          border: '1px solid var(--border-subtle)',
          borderRadius: 12, overflow: 'hidden',
          marginBottom: 2,
          opacity: revealed ? 1 : 0,
          transform: revealed ? 'translateY(0)' : 'translateY(16px)',
          transition: 'all 0.6s var(--ease-expo) 0.1s',
        }} className="ind-tabs">
          {INDUSTRIES.map((ind, idx) => {
            const isActive = active === ind.id;
            return (
              <button
                key={ind.id}
                onClick={() => setActive(ind.id)}
                className={isActive ? 'ind-tab-active' : 'ind-tab-inactive'}
                style={{
                  flex: 1, border: 'none', cursor: 'pointer',
                  padding: '18px 16px',
                  background: isActive ? 'var(--bg-tertiary)' : 'transparent',
                  borderRight: idx < INDUSTRIES.length - 1 ? '1px solid var(--border-subtle)' : 'none',
                  borderBottom: isActive ? `2px solid ${ind.color}` : '2px solid transparent',
                  transition: 'all 0.25s ease',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                }}
                onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = 'rgba(255,255,255,0.02)'; }}
                onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}
              >
                <span style={{
                  fontSize: 20,
                  color: isActive ? ind.color : 'var(--text-tertiary)',
                  transition: 'color 0.25s ease',
                }}>{ind.icon}</span>
                <span style={{
                  fontFamily: 'var(--font-sans)', fontSize: 13, fontWeight: 500,
                  color: isActive ? 'var(--text-primary)' : 'var(--text-secondary)',
                  transition: 'color 0.25s ease',
                  whiteSpace: 'nowrap',
                }}>{ind.name}</span>
                <span style={{
                  fontFamily: 'var(--font-mono)', fontSize: 10,
                  color: isActive ? ind.color : 'var(--text-tertiary)',
                  transition: 'color 0.25s ease',
                  textAlign: 'center',
                  lineHeight: 1.3,
                }}>{ind.tagline}</span>
              </button>
            );
          })}
        </div>

        {/* Expanded detail panel */}
        {activeData && (
          <div key={activeData.id} className="ind-panel" style={{
            background: 'var(--bg-secondary)',
            border: `1px solid ${activeData.color}30`,
            borderTop: `2px solid ${activeData.color}`,
            borderRadius: '0 0 12px 12px',
            padding: '40px 40px',
            opacity: revealed ? 1 : 0,
            transition: 'opacity 0.4s ease, border-color 0.3s ease',
            animation: 'panel-in 0.4s var(--ease-expo)',
          }}>
            <div style={{
              display: 'grid',
              gridTemplateColumns: '1fr 1fr',
              gap: 48,
            }} className="ind-grid">
              {/* Left: Pains */}
              <div>
                <div style={{
                  fontFamily: 'var(--font-mono)', fontSize: 11,
                  color: activeData.color, letterSpacing: '0.1em',
                  marginBottom: 20,
                }}>{activeData.tag} · PAIN POINTS</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                  {activeData.pains.map((pain, i) => (
                    <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                      <span style={{
                        fontFamily: 'var(--font-mono)', fontSize: 12,
                        color: activeData.color, opacity: 0.7,
                        marginTop: 2, minWidth: 20,
                      }}>0{i + 1}</span>
                      <span style={{
                        fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.55,
                      }}>{pain}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Right: Solutions + Outcome */}
              <div>
                <div style={{
                  fontFamily: 'var(--font-mono)', fontSize: 11,
                  color: activeData.color, letterSpacing: '0.1em',
                  marginBottom: 20,
                }}>{activeData.tag} · WHAT WE BUILD</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 28 }}>
                  {activeData.solutions.map((sol, i) => (
                    <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                      <span style={{
                        width: 16, height: 16, borderRadius: '50%',
                        border: `1.5px solid ${activeData.color}`,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        flexShrink: 0, marginTop: 2,
                        background: `${activeData.color}15`,
                      }}>
                        <span style={{ fontSize: 8, color: activeData.color }}>✓</span>
                      </span>
                      <span style={{
                        fontSize: 14, color: 'var(--text-primary)', lineHeight: 1.55,
                      }}>{sol}</span>
                    </div>
                  ))}
                </div>

                {/* Big metric + quote, high-conversion conversion proof */}
                {activeData.metric && (
                  <div style={{
                    background: `linear-gradient(135deg, ${activeData.color}14, ${activeData.color}04)`,
                    border: `1px solid ${activeData.color}40`,
                    borderRadius: 10, padding: '18px 20px', marginBottom: 14,
                  }}>
                    <div style={{
                      fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
                      color: activeData.color, letterSpacing: '0.1em', marginBottom: 8,
                    }}>// REAL CLIENT METRIC</div>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, flexWrap: 'wrap' }}>
                      <span style={{
                        fontFamily: 'Syne, sans-serif', fontSize: 38, fontWeight: 700,
                        color: activeData.color, letterSpacing: '-0.02em', lineHeight: 1,
                      }}>{activeData.metric.value}</span>
                      <span style={{
                        fontFamily: 'Inter, sans-serif', fontSize: 13,
                        color: 'var(--text-secondary)', lineHeight: 1.4,
                      }}>{activeData.metric.label}</span>
                    </div>
                  </div>
                )}

                {activeData.quote && (
                  <div style={{
                    padding: '14px 18px',
                    background: 'var(--bg-tertiary)',
                    borderLeft: `3px solid ${activeData.color}`,
                    borderRadius: '0 8px 8px 0', marginBottom: 14,
                  }}>
                    <div style={{
                      fontFamily: 'Syne, sans-serif', fontSize: 14,
                      color: 'var(--text-primary)', lineHeight: 1.5,
                      fontStyle: 'italic', fontWeight: 500, marginBottom: 6,
                    }}>"{activeData.quote.text}"</div>
                    <div style={{
                      fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
                      color: 'var(--text-tertiary)', letterSpacing: '0.06em',
                    }}>, {activeData.quote.author}</div>
                  </div>
                )}

                {/* Outcome + CTA */}
                <div style={{
                  background: `${activeData.color}0A`,
                  border: `1px solid ${activeData.color}30`,
                  borderRadius: 8, padding: '14px 18px',
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  gap: 16,
                }}>
                  <div>
                    <div style={{
                      fontFamily: 'var(--font-mono)', fontSize: 10,
                      color: activeData.color, letterSpacing: '0.08em',
                      marginBottom: 4,
                    }}>OUTCOME PATTERN</div>
                    <span style={{
                      fontSize: 13, color: 'var(--text-primary)', lineHeight: 1.4,
                      fontStyle: 'italic',
                    }}>{activeData.outcome}</span>
                  </div>
                  <a href="#work"
                    onClick={e => {
                      e.preventDefault();
                      // Map industry name to niche filter key
                      const map = {
                        'Med Spas':    'Med Spa',
                        'CPA Firms':   'CPA',
                        'Real Estate': 'Real Estate',
                        'Law Firms':   'Law Firm',
                        'Retail & E-com': 'All builds',
                      };
                      const niche = map[activeData.name] || 'All builds';
                      if (window.__filterCaseStudies) {
                        window.__filterCaseStudies(niche);
                      } else {
                        document.querySelector('#work')?.scrollIntoView({behavior:'smooth'});
                      }
                    }}
                    style={{
                    fontFamily: 'var(--font-mono)', fontSize: 11,
                    color: activeData.color, textDecoration: 'none',
                    whiteSpace: 'nowrap', opacity: 0.8,
                    transition: 'opacity 0.2s ease',
                    flexShrink: 0,
                  }}
                  onMouseEnter={e => e.target.style.opacity = '1'}
                  onMouseLeave={e => e.target.style.opacity = '0.8'}
                  >{activeData.cta}</a>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Other industries CTA, don't exclude anyone */}
        <div style={{
          marginTop: 40,
          opacity: revealed ? 1 : 0,
          transition: 'opacity 0.6s ease 0.4s',
          display: 'grid', gridTemplateColumns: '1fr auto',
          gap: 32, alignItems: 'center',
          background: 'var(--bg-secondary)',
          border: '1px solid var(--border-subtle)',
          borderRadius: 12, padding: '24px 28px',
          flexWrap: 'wrap',
        }} className="ind-other">
          <div>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
              color: 'var(--accent-mint-text)', letterSpacing: '0.1em', marginBottom: 8,
            }}>// NOT IN THE LIST?</div>
            <p style={{
              fontFamily: 'Inter, sans-serif', fontSize: 15,
              color: 'var(--text-primary)', lineHeight: 1.5, marginBottom: 6,
              fontWeight: 500,
            }}>
              We work across every B2B vertical. If your business has repetitive, high-stakes workflows, there's almost certainly an AI system worth building.
            </p>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 10 }}>
              {['Healthcare', 'Dental', 'Property Mgmt', 'Insurance', 'Construction', 'Financial Advisory', 'Logistics', 'Staffing', 'B2B SaaS'].map(v => (
                <span key={v} style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
                  color: 'var(--text-tertiary)', padding: '3px 10px',
                  border: '1px solid var(--border-subtle)', borderRadius: 20,
                  background: 'var(--bg-tertiary)',
                }}>{v}</span>
              ))}
            </div>
          </div>
          <a href="https://cal.com/ratan-kumar/ai-automation-startegy-call-with-ratan-quantaeight"
            target="_blank" rel="noopener"
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '12px 22px', background: 'var(--accent-mint)',
              color: '#0A0A0B', borderRadius: 8, textDecoration: 'none',
              fontFamily: 'Inter, sans-serif', fontSize: 13, fontWeight: 700,
              transition: 'opacity 0.2s ease', whiteSpace: 'nowrap', flexShrink: 0,
            }}
            onMouseEnter={e => e.currentTarget.style.opacity = '0.85'}
            onMouseLeave={e => e.currentTarget.style.opacity = '1'}
          >Tell us your industry →</a>
        </div>
      </div>

      <style>{`
        @keyframes panel-in {
          from { opacity: 0; transform: translateY(-8px); }
          to { opacity: 1; transform: translateY(0); }
        }
        /* Tablet */
        @media (max-width: 900px) {
          .ind-grid { grid-template-columns: 1fr !important; gap: 28px !important; }
          .ind-other { grid-template-columns: 1fr !important; gap: 20px !important; }
          .ind-other a { width: 100% !important; text-align: center !important; justify-content: center !important; }
        }
        /* Mobile: pill selector strip */
        @media (max-width: 600px) {
          .ind-tabs {
            display: flex !important;
            flex-wrap: nowrap !important;
            overflow-x: auto !important;
            -webkit-overflow-scrolling: touch !important;
            scrollbar-width: none !important;
            gap: 8px !important;
            padding: 0 0 4px 0 !important;
            background: transparent !important;
            border: none !important;
            border-radius: 0 !important;
          }
          .ind-tabs::-webkit-scrollbar { display: none; }
          .ind-tabs button {
            flex: 0 0 auto !important;
            padding: 8px 16px !important;
            border-radius: 100px !important;
            border-right: none !important;
            border-bottom: none !important;
            gap: 4px !important;
            flex-direction: row !important;
            align-items: center !important;
            white-space: nowrap !important;
            min-height: unset !important;
          }
          .ind-tabs button span:last-child { display: none !important; }
          .ind-tab-active {
            background: var(--bg-tertiary) !important;
            border: 1px solid var(--border-emphasis) !important;
          }
          .ind-tab-inactive {
            background: var(--bg-secondary) !important;
            border: 1px solid var(--border-subtle) !important;
          }
          .ind-panel {
            border-radius: 12px !important;
            padding: 24px 20px !important;
            margin-top: 12px !important;
          }
          .ind-other {
            flex-direction: column !important;
            gap: 16px !important;
            padding: 20px !important;
          }
          .ind-other a {
            width: 100% !important;
            text-align: center !important;
            justify-content: center !important;
          }
        }
      `}</style>
    </section>
  );
}

Object.assign(window, { IndustrySelector });
