/* Pricing calculator + industry tabs + scroll reveals + nav + stat counters */
const { useState: useStatePC, useEffect: useEffectPC, useRef: useRefPC } = React;

function CountUp({ to, prefix = '', suffix = '', duration = 1600 }) {
  const [val, setVal] = useStatePC(0);
  const ref = useRefPC(null);
  const started = useRefPC(false);
  useEffectPC(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const tick = (now) => {
            const p = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setVal(Math.round(to * eased));
            if (p < 1) requestAnimationFrame(tick);
          };
          requestAnimationFrame(tick);
        }
      });
    }, { threshold: 0.4 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, [to, duration]);
  return <span ref={ref}>{prefix}{val.toLocaleString()}{suffix}</span>;
}

function LeadsStats() {
  const stats = [
    { num: 80, suffix: '%', label: 'of callers hang up rather than leave a voicemail' },
    { num: 78, suffix: '%', label: 'of leads go with the first business to respond' },
    { num: 62, suffix: '%', label: 'of inbound calls to SMBs happen after business hours' },
    { num: 42, prefix: '$', suffix: 'K', label: 'average annual revenue lost per missed lead source' }
  ];
  return (
    <div className="leads-grid">
      {stats.map((s, i) => (
        <div className="lead-stat" key={i}>
          <div className="lead-stat-num">
            <CountUp to={s.num} prefix={s.prefix} />
            <span className="stat-unit">{s.suffix}</span>
          </div>
          <div className="lead-stat-label">{s.label}</div>
        </div>
      ))}
    </div>
  );
}

function PricingCalculator() {
  const [calls, setCalls] = useStatePC(40);
  const [duration, setDuration] = useStatePC(3);
  const [ticket, setTicket] = useStatePC(450);
  const [closeRate, setCloseRate] = useStatePC(25);

  const callsPerMonth = calls * 22; // weekdays approx
  const minutesPerMonth = callsPerMonth * duration;
  const missedWithoutAI = Math.round(callsPerMonth * 0.4); // ~40% go to VM
  const recoveredRevenue = Math.round(missedWithoutAI * (closeRate / 100) * ticket);

  // Pick the right plan
  let plan = 'Starter';
  let planCost = 99;
  let included = 100;
  let overage = 0.75;
  if (minutesPerMonth > 100 && minutesPerMonth <= 300) { plan = 'Growth'; planCost = 199; included = 300; overage = 0.75; }
  else if (minutesPerMonth > 300) { plan = 'Pro'; planCost = 399; included = 800; overage = 0.60; }
  const overMinutes = Math.max(0, minutesPerMonth - included);
  const overageCost = Math.round(overMinutes * overage);
  const monthlyCost = planCost + overageCost;
  const roi = recoveredRevenue > 0 ? Math.round(recoveredRevenue / monthlyCost) : 0;

  return (
    <div className="pricing-grid">
      <div className="calc">
        <div className="calc-label">ROI Calculator</div>

        <div className="calc-slider-group">
          <div className="calc-slider-row">
            <span>Daily inbound calls</span>
            <span><span className="calc-slider-val">{calls}</span> <span className="calc-slider-unit">calls/day</span></span>
          </div>
          <input type="range" min="5" max="200" value={calls} onChange={(e) => setCalls(+e.target.value)} />
        </div>

        <div className="calc-slider-group">
          <div className="calc-slider-row">
            <span>Avg call length</span>
            <span><span className="calc-slider-val">{duration}</span> <span className="calc-slider-unit">min</span></span>
          </div>
          <input type="range" min="1" max="8" step="0.5" value={duration} onChange={(e) => setDuration(+e.target.value)} />
        </div>

        <div className="calc-slider-group">
          <div className="calc-slider-row">
            <span>Avg job value</span>
            <span><span className="calc-slider-val">${ticket}</span></span>
          </div>
          <input type="range" min="50" max="5000" step="50" value={ticket} onChange={(e) => setTicket(+e.target.value)} />
        </div>

        <div className="calc-slider-group">
          <div className="calc-slider-row">
            <span>Close rate on answered calls</span>
            <span><span className="calc-slider-val">{closeRate}</span> <span className="calc-slider-unit">%</span></span>
          </div>
          <input type="range" min="5" max="60" value={closeRate} onChange={(e) => setCloseRate(+e.target.value)} />
        </div>

        <div className="calc-breakdown">
          <div className="calc-line"><span>Recommended plan</span><span className="calc-line-val">{plan} · ${planCost}/mo</span></div>
          <div className="calc-line"><span>Projected minutes / mo</span><span className="calc-line-val">{minutesPerMonth.toLocaleString()}</span></div>
          <div className="calc-line"><span>Overage ({overMinutes} min × ${overage.toFixed(2)})</span><span className="calc-line-val">${overageCost.toLocaleString()}</span></div>
          <div className="calc-line big"><span>Est. monthly investment</span><span className="calc-line-val">${monthlyCost.toLocaleString()}</span></div>
        </div>

        <div className="calc-verdict">
          Based on your volume, we'd recover roughly <strong>{missedWithoutAI} leads/mo</strong> that today go to voicemail — worth <strong>${recoveredRevenue.toLocaleString()}/mo</strong>. That's an estimated <strong>{roi}× return</strong> on ClearShield.
        </div>
      </div>

      <div className="plans">
        <div className={`plan ${plan === 'Starter' ? 'featured' : ''}`}>
          <div>
            <div className="plan-name">Starter {plan === 'Starter' && <span className="plan-badge">Match</span>}</div>
            <div className="plan-desc">Backup coverage or light daily volume</div>
          </div>
          <div className="plan-mins">100 min / mo<br />$0.75 overage</div>
          <div>
            <div className="plan-price">$99</div>
            <div className="plan-price-sub">/ month</div>
          </div>
        </div>
        <div className={`plan ${plan === 'Growth' ? 'featured' : ''}`}>
          <div>
            <div className="plan-name">Growth {plan === 'Growth' && <span className="plan-badge">Match</span>}</div>
            <div className="plan-desc">Service businesses with daily inbound</div>
          </div>
          <div className="plan-mins">300 min / mo<br />$0.75 overage</div>
          <div>
            <div className="plan-price">$199</div>
            <div className="plan-price-sub">/ month</div>
          </div>
        </div>
        <div className={`plan ${plan === 'Pro' ? 'featured' : ''}`}>
          <div>
            <div className="plan-name">Pro {plan === 'Pro' && <span className="plan-badge">Match</span>}</div>
            <div className="plan-desc">High volume or companies running ads</div>
          </div>
          <div className="plan-mins">800 min / mo<br />$0.60 overage</div>
          <div>
            <div className="plan-price">$399</div>
            <div className="plan-price-sub">/ month</div>
          </div>
        </div>

        <div className="pricing-foot">
          <span>Setup fee waived (launch special)</span>
          <span>Go live in 3–7 days</span>
          <span>Cancel anytime</span>
          <span>Keep your number</span>
        </div>
      </div>
    </div>
  );
}

const INDUSTRIES = [
  {
    key: 'healthcare', name: 'Healthcare',
    headline: 'Patient data is sacred. Your phones should be, too.',
    lead: "HIPAA-aware intake, EHR-focused awareness training, and an AI front desk that speaks clinical language — never a transcription mistake on a medication.",
    stat: { num: '32%', lbl: 'of U.S. data breaches are healthcare' },
    left: {
      title: 'Threats you face',
      items: [
        'Patient data breaches across EHR systems',
        'Phishing targeting clinical staff',
        'Ransomware that halts clinical operations',
        'HIPAA penalties up to $1.5M per category'
      ]
    },
    right: {
      title: 'How we help',
      items: [
        'HIPAA security risk assessments with remediation',
        'Staff training tailored to EHR workflows',
        'Phishing simulations mimicking healthcare patterns',
        'Incident response matching breach notification rules'
      ]
    }
  },
  {
    key: 'finance', name: 'Financial Services',
    headline: 'Compliance-ready, fraud-aware, audit-calm.',
    lead: "BEC-resistant workflows, PCI-DSS readiness, and AI agents that speak the language of wealth managers, credit unions, and accounting firms.",
    stat: { num: '$2.77B', lbl: 'industry BEC losses' },
    left: {
      title: 'Threats you face',
      items: [
        'Business email compromise targeting partners',
        'PCI DSS 4.0.1 compliance (mandatory since April 2025)',
        'Client financial data theft & credential harvesting',
        'SOX, GLBA, and state-level audit pressure'
      ]
    },
    right: {
      title: 'How we help',
      items: [
        'PCI DSS and SOX compliance readiness',
        'BEC-focused phishing simulations for finance teams',
        'Access control reviews & vendor risk management',
        'Audit docs structured the way regulators expect'
      ]
    }
  },
  {
    key: 'manufacturing', name: 'Manufacturing',
    headline: 'From the office to the production floor.',
    lead: "IT/OT security that respects the shop floor, IP protection, and AI agents that know the difference between an RFQ and a service dispatch.",
    stat: { num: '68%', lbl: 'of industrial ransomware hits manufacturing' },
    left: {
      title: 'Threats you face',
      items: [
        'Ransomware targeting production systems',
        'IP theft of proprietary designs & processes',
        'OT vulnerabilities in connected equipment',
        'Supply chain & vendor-introduced risk'
      ]
    },
    right: {
      title: 'How we help',
      items: [
        'IT/OT assessments covering both office and floor',
        'Ransomware prevention & recovery planning',
        'IP protection strategies & access hardening',
        'CMMC readiness for defense supply chain'
      ]
    }
  },
  {
    key: 'professional', name: 'Professional Services',
    headline: 'Confidentiality is your product.',
    lead: "Security policies for hybrid teams, encrypted client comms, and AI agents trained on the ethical weight of privileged information.",
    stat: { num: '78%', lbl: 'of firms report BEC attempts monthly' },
    left: {
      title: 'Threats you face',
      items: [
        'Client data exposure & confidential comm breaches',
        'BEC targeting partners and senior staff',
        'Remote-access & personal-device vulnerabilities',
        'Ethical obligations around privileged info'
      ]
    },
    right: {
      title: 'How we help',
      items: [
        'Security policies for mobile & hybrid work',
        'Email security & encryption for client comms',
        'Training focused on social engineering & BEC',
        'Data classification & confidential access control'
      ]
    }
  },
  {
    key: 'realestate', name: 'Real Estate',
    headline: "Wire fraud is the industry's #1 risk. We shut it down.",
    lead: "Closing-process hardening, deepfake-aware verification, and AI agents that capture lead details without handing them to a BEC attacker.",
    stat: { num: '$500M+', lbl: 'in U.S. wire fraud losses in 2024' },
    left: {
      title: 'Threats you face',
      items: [
        'Wire fraud — the industry\'s most devastating risk',
        'Deepfake voice cloning during closings (700% surge)',
        'BEC impersonating title companies or buyers',
        'Client personal & financial data theft'
      ]
    },
    right: {
      title: 'How we help',
      items: [
        'Wire fraud prevention & verification procedures',
        'Email security for closing & fund transfers',
        'Real-estate-specific phishing simulations',
        'Client data protection & secure comm tools'
      ]
    }
  }
];

function Industries() {
  const [active, setActive] = useStatePC('healthcare');
  return (
    <>
      <div className="ind-tabs">
        {INDUSTRIES.map((ind) => (
          <button key={ind.key} className={`ind-tab ${active === ind.key ? 'active' : ''}`} onClick={() => setActive(ind.key)}>
            {ind.name}
          </button>
        ))}
      </div>
      {INDUSTRIES.map((ind) => (
        <div key={ind.key} className={`ind-panel ${active === ind.key ? 'active' : ''}`}>
          <div className="ind-lead">
            <h3>{ind.headline}</h3>
            <p>{ind.lead}</p>
            <div className="ind-lead-stat">
              <div className="num">{ind.stat.num}</div>
              <div className="lbl">{ind.stat.lbl}</div>
            </div>
          </div>
          <div className="ind-col">
            <h5>{ind.left.title}</h5>
            <ul>{ind.left.items.map((it, i) => <li key={i}>{it}</li>)}</ul>
          </div>
          <div className="ind-col">
            <h5>{ind.right.title}</h5>
            <ul>{ind.right.items.map((it, i) => <li key={i}>{it}</li>)}</ul>
          </div>
        </div>
      ))}
    </>
  );
}

window.LeadsStats = LeadsStats;
window.PricingCalculator = PricingCalculator;
window.Industries = Industries;
window.CountUp = CountUp;
