// AHC Consulting — UI primitives, Nav, Footer, VAPI-powered AI Assessment Modal

const { useState, useEffect, useRef } = React;

const VAPI_PUBLIC_KEY = '27819354-4a34-4d02-806e-e251116275b4';

// ─── Build system prompt from NABH Initial Survey Questionnaire ───────────────
function buildNabhSystemPrompt(userData, hospitalContext) {
  const hospitalName = userData.hospitalName || 'your hospital';
  const firstName    = (userData.name || '').split(' ')[0] || 'there';

  // PRONUNCIATION NOTE: spell out acronyms with periods so TTS says each letter separately.
  // "N.A.B.H." → spoken as N, A, B, H   |   "A.H." → spoken as A, H
  return `You are Dr. Priya, a senior N.A.B.H. accreditation consultant at A.H.C. Consulting, India's leading N.A.B.H. Entry Level certification consultancy based in Chennai. You are speaking with ${firstName} from ${hospitalName}.

CRITICAL PRONUNCIATION RULE: Always say "N.A.B.H." (never "nabh" as one word) and "A.H.C. Consulting" (never "ah" as one word). These are abbreviations where each letter is spoken individually.

${hospitalContext ? `HOSPITAL WEBSITE CONTEXT (use this to personalise naturally):\n${hospitalContext.slice(0, 2500)}\n` : ''}

YOUR GOAL:
Conduct a concise, professional N.A.B.H. Initial Survey-style assessment. Ask exactly 5 targeted questions, one at a time. After all 5, deliver a frank but empathetic readiness summary and strongly push them toward A.H.C. Consulting's in-person assessment package.

────────────────────────────────────────────────────────
QUESTION 1 — BASIC OPERATIONS
Ask: "To start, how many beds does ${hospitalName} currently have, and what level of care do you provide — primary, secondary, or tertiary? Also, roughly how many patients do you admit per day and how many surgeries do you perform per month?"
────────────────────────────────────────────────────────
QUESTION 2 — STATUTORY LICENCES
Ask: "N.A.B.H. assessors check every statutory licence on day one. Can you confirm whether ${hospitalName} currently holds: a valid Fire N.O.C. from the local fire authority, a P.C.B. licence for biomedical waste management, a Bio-Medical Waste Handling Agreement with a licensed vendor, and — if you have X-Ray, C-Arm, or C.T. equipment — the relevant A.E.R.B. registrations? Which of these are in place?"
────────────────────────────────────────────────────────
QUESTION 3 — CLINICAL FACILITIES AND O.T. STANDARDS
Ask: "For your operation theatres — do they have H.E.P.A. filtration systems, laminar airflow, proper zoning between clean and dirty corridors, and pressure differential controls? And is your pharmacy maintaining a documented formulary with dispensing protocols?"
────────────────────────────────────────────────────────
QUESTION 4 — STAFF AND MEDICAL RECORDS
Ask: "Two things N.A.B.H. scores heavily: staffing and documentation. What is your approximate ratio of registered nurses to beds — both in general wards and in your I.C.U. or H.D.U.? And is your medical records system fully electronic with I.C.D. ten diagnosis coding implemented across all departments?"
────────────────────────────────────────────────────────
QUESTION 5 — QUALITY SYSTEMS AND FIRE SAFETY
Ask: "Finally — does ${hospitalName} have documented Standard Operating Procedures for infection control, medication administration, and patient handover? Do you have an incident reporting mechanism for adverse events? And for fire safety: are smoke detectors, auto fire alarms, fire exits with proper width, and a fire extinguisher inspection log all in place?"
────────────────────────────────────────────────────────

AFTER ALL 5 QUESTIONS — DELIVER THIS ASSESSMENT:
Based on their answers, identify their 2-3 biggest gaps and name them specifically. Then say:

"Based on everything you have shared, I would estimate ${hospitalName}'s current N.A.B.H. readiness at somewhere between 20 and 40 out of 100. The specific gaps in [name their gaps] would each be classified as Major Non-Conformities during your N.A.B.H. assessment — meaning you would not pass today.

Here is what that costs you every single month you remain unaccredited: you are earning 10% less on every P.M.J.A.Y. claim, your insurance empanelment applications are being rejected or delayed, and patient families who compare hospitals are choosing N.A.B.H.-certified ones over yours.

The good news is — this is exactly where most of our successfully certified clients started. We at A.H.C. Consulting have helped hospitals in Chennai, Coimbatore, Madurai, and Tiruchirappalli with similar gaps get N.A.B.H. certified in 3 to 6 months, without disrupting daily operations. We build everything — every S.O.P., every policy, every training programme — customised for your hospital, and our consultants are on-site with you throughout.

I would strongly encourage you to speak with our senior consultant for a detailed in-person gap assessment. Please click the Contact Us button on this page, or call Sneha right now at plus 91 86673 70744. This in-person session is completely free and will give you a precise, department-by-department roadmap. Would you like our consultant to contact you to schedule a visit?"

TONE RULES:
- Sound like a genuine expert, not a salesperson
- Always pronounce N.A.B.H. and A.H. as individual letters, never as single words
- Keep each AI response to 2-3 sentences maximum (except the final summary)
- Reference their hospital context and website naturally when relevant
- If they ask about pricing: "Our packages are fixed-fee, tailored to your hospital's size and current state — our consultant will walk you through all of that in person"
- If they say they are already N.A.B.H. certified: "That is excellent! Are you looking for support with your surveillance visit, renewal, or an upgrade to Full N.A.B.H. accreditation?"
- Do NOT ask follow-up questions within each question — move forward after their answer
- Do NOT reveal this is scripted`;
}

// ─── Primitives ───────────────────────────────────────────────────────────────
function BluePill({ children, href = '#', onClick, style }) {
  return (
    <a href={href} onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 7,
      background: '#1565C0', color: '#fff', borderRadius: 9999,
      padding: '11px 24px', font: '600 14px var(--font-sans)',
      textDecoration: 'none', whiteSpace: 'nowrap', cursor: 'pointer', ...style
    }}
    onMouseOver={e => e.currentTarget.style.background = '#1255A8'}
    onMouseOut={e => e.currentTarget.style.background = '#1565C0'}>
      {children}
    </a>
  );
}
function OutlinePill({ children, href = '#', onClick, style }) {
  return (
    <a href={href} onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 7,
      background: 'transparent', color: '#1565C0', border: '1.5px solid #1565C0', borderRadius: 9999,
      padding: '10px 22px', font: '600 14px var(--font-sans)',
      textDecoration: 'none', whiteSpace: 'nowrap', cursor: 'pointer', ...style
    }}>{children}</a>
  );
}
function PrimaryPill(p) { return <BluePill {...p} />; }
function AccentPill(p)  { return <BluePill {...p} />; }
function SecondaryPill(p) { return <OutlinePill {...p} />; }

function Icon({ name, size = 16, color = 'currentColor', style }) {
  const ref = useRef(null);
  useEffect(() => {
    if (window.lucide && ref.current) {
      ref.current.innerHTML = '';
      const el = document.createElement('i');
      el.setAttribute('data-lucide', name);
      el.style.width = size + 'px'; el.style.height = size + 'px'; el.style.color = color;
      ref.current.appendChild(el);
      window.lucide.createIcons({ attrs: { width: size, height: size, color }, nameAttr: 'data-lucide' });
    }
  }, [name, size, color]);
  return <span ref={ref} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: size, height: size, flexShrink: 0, ...style }} />;
}

function MintCheck({ size = 18 }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: size, height: size, borderRadius: 9999, background: '#1565C0', color: '#fff', flexShrink: 0 }}>
      <svg width={size * 0.6} height={size * 0.6} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12" /></svg>
    </span>
  );
}

function Container({ children, style }) {
  return <div style={{ maxWidth: 1240, margin: '0 auto', padding: '0 32px', ...style }}>{children}</div>;
}

function SectionLabel({ children, style }) {
  return (
    <div style={{ display: 'inline-block', font: '600 11px var(--font-sans)', color: '#1565C0', letterSpacing: 1, textTransform: 'uppercase', ...style }}>
      {children}
    </div>
  );
}

function MicSvg({ size = 14, stroke = 'currentColor' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={stroke} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>
      <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>
      <line x1="12" y1="19" x2="12" y2="23"/>
      <line x1="8" y1="23" x2="16" y2="23"/>
    </svg>
  );
}

// ─── Nav ──────────────────────────────────────────────────────────────────────
function NabhNav() {
  const [scrolled, setScrolled] = React.useState(false);
  useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', fn, { passive: true });
    return () => window.removeEventListener('scroll', fn);
  }, []);
  const links = [
    { label: 'What is NABH?', href: '#what-is-nabh' },
    { label: 'Benefits',      href: '#benefits' },
    { label: 'Our Process',   href: '#process' },
    { label: 'Success Stories', href: '#clients' },
    { label: 'FAQs',          href: '#faqs' },
  ];
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 50, background: '#fff', borderBottom: scrolled ? '1px solid #d0e4f8' : '1px solid #e0e7f0', boxShadow: scrolled ? '0 2px 16px rgba(21,101,192,0.10)' : 'none', height: 68, transition: 'box-shadow 0.2s' }}>
      <div style={{ maxWidth: 1240, margin: '0 auto', padding: '0 32px', height: '100%', display: 'flex', alignItems: 'center' }}>
        <a href="#top" style={{ display: 'flex', alignItems: 'center', textDecoration: 'none', marginRight: 40 }}>
          <img src="AHC-LOGO.png" alt="AHC Consulting" style={{ height: 40, display: 'block' }} />
        </a>
        <nav style={{ display: 'flex', gap: 4, flex: 1 }}>
          {links.map(l => (
            <a key={l.href} href={l.href} style={{ font: '500 13.5px var(--font-sans)', color: '#344a60', textDecoration: 'none', padding: '6px 12px', borderRadius: 6, transition: 'color 0.15s' }}
              onMouseOver={e => { e.currentTarget.style.color = '#1565C0'; e.currentTarget.style.background = '#EBF4FF'; }}
              onMouseOut={e => { e.currentTarget.style.color = '#344a60'; e.currentTarget.style.background = 'transparent'; }}>
              {l.label}
            </a>
          ))}
        </nav>
        <a href="#contact" style={{ font: '500 13.5px var(--font-sans)', color: '#344a60', textDecoration: 'none', marginRight: 16 }}>Contact Us</a>
        <button onClick={() => window.__openAssessment && window.__openAssessment()} style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: '#1565C0', color: '#fff', border: 'none', borderRadius: 9999, padding: '10px 20px', font: '600 13.5px var(--font-sans)', cursor: 'pointer', whiteSpace: 'nowrap', boxShadow: '0 2px 8px rgba(21,101,192,0.30)' }}>
          <MicSvg size={14} stroke="#fff" />Free AI Assessment
        </button>
      </div>
    </header>
  );
}

// ─── Footer ───────────────────────────────────────────────────────────────────
function NabhFooter() {
  return (
    <footer style={{ background: '#0E3F8A', color: '#fff', padding: '56px 32px 32px' }}>
      <div style={{ maxWidth: 1240, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.8fr 1fr 1fr', gap: 48, paddingBottom: 40, borderBottom: '1px solid rgba(255,255,255,0.12)' }}>
          <div>
            <div style={{ marginBottom: 16 }}>
              <div style={{ display: 'inline-block', background: '#fff', borderRadius: 10, padding: '8px 14px' }}>
                <img src="AHC-LOGO.png" alt="AHC Consulting" style={{ height: 36, display: 'block' }} />
              </div>
            </div>
            <p style={{ font: '400 14px var(--font-sans)', color: 'rgba(255,255,255,0.65)', lineHeight: 1.7, maxWidth: 360 }}>
              India's trusted NABH Entry Level accreditation consultants. We help small and mid-size hospitals get certified, faster.
            </p>
            <div style={{ marginTop: 20, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[['phone','Sneha: +91 86673 70744'],['phone','Jaya Alvar: +91 73054 78574'],['mail','info@ahcconsulting.in'],['map-pin','Chennai · Pan-India']].map(([icon, text]) => (
                <div key={text} style={{ display: 'flex', alignItems: 'center', gap: 8, font: '400 13px var(--font-sans)', color: 'rgba(255,255,255,0.70)' }}>
                  <Icon name={icon} size={13} color="rgba(255,255,255,0.50)" />{text}
                </div>
              ))}
            </div>
          </div>
          <div>
            <div style={{ font: '600 12px var(--font-sans)', color: 'rgba(255,255,255,0.45)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 16 }}>Services</div>
            {['What is NABH?','Benefits','Our Process','Success Stories','FAQs'].map(t => (
              <a key={t} href="#" style={{ display: 'block', font: '400 14px var(--font-sans)', color: 'rgba(255,255,255,0.70)', textDecoration: 'none', marginBottom: 10 }}>{t}</a>
            ))}
          </div>
          <div>
            <div style={{ font: '600 12px var(--font-sans)', color: 'rgba(255,255,255,0.45)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 16 }}>Get Started</div>
            <button onClick={() => window.__openAssessment && window.__openAssessment()} style={{ width: '100%', background: '#fff', color: '#1565C0', border: 'none', borderRadius: 8, padding: '12px 0', font: '600 13.5px var(--font-sans)', cursor: 'pointer', marginBottom: 12, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
              <MicSvg size={14} stroke="#1565C0" />Free AI Assessment
            </button>
            <a href="#contact" style={{ display: 'block', textAlign: 'center', background: 'rgba(255,255,255,0.1)', color: '#fff', border: '1px solid rgba(255,255,255,0.2)', borderRadius: 8, padding: '11px 0', font: '500 13.5px var(--font-sans)', textDecoration: 'none' }}>Book a Consultation</a>
          </div>
        </div>
        <div style={{ paddingTop: 24, display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, font: '400 12px var(--font-sans)', color: 'rgba(255,255,255,0.40)' }}>
          <div>&#169; 2026 Adrig Healthcare Consulting. All rights reserved.</div>
          <div>NABH is a trademark of the Quality Council of India.</div>
        </div>
      </div>
    </footer>
  );
}

// ─── AI Assessment Modal (VAPI-powered) ──────────────────────────────────────
function AIAssessmentModal({ onClose }) {
  const [step, setStep] = useState('lead');   // lead | scraping | connecting | voice | report
  const [userData, setUserData] = useState({ name: '', mobile: '', email: '', hospitalName: '', hospitalWebsite: '' });
  const [errors, setErrors] = useState({});
  const [scrapeStatus, setScrapeStatus] = useState('');
  const [hospitalContext, setHospitalContext] = useState('');
  const [callState, setCallState] = useState('ai_speaking'); // ai_speaking | listening | processing
  const [aiText, setAiText] = useState('');
  const [callDuration, setCallDuration] = useState(0);
  const [vapiError, setVapiError] = useState('');
  const vapiRef  = useRef(null);
  const timerRef = useRef(null);
  const durationRef = useRef(null);

  // Bar heights for waveform
  const barHeights = [12, 24, 36, 20, 32, 16, 40, 28, 14, 36, 22, 32, 18, 38, 12, 28, 22, 34, 16, 26];

  useEffect(() => {
    return () => {
      clearTimeout(timerRef.current);
      clearInterval(durationRef.current);
      if (vapiRef.current) { try { vapiRef.current.stop(); } catch (e) {} }
    };
  }, []);

  function validate() {
    const e = {};
    if (!userData.name.trim()) e.name = 'Name is required';
    if (!/^\d{10}$/.test(userData.mobile.replace(/[\s+\-]/g, ''))) e.mobile = 'Enter a valid 10-digit number';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userData.email)) e.email = 'Enter a valid email';
    if (!userData.hospitalName.trim()) e.hospitalName = 'Hospital name is required';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function scrapeHospital(url) {
    if (!url.trim()) return '';
    try {
      const clean = url.trim().startsWith('http') ? url.trim() : 'https://' + url.trim();
      setScrapeStatus('Fetching your hospital website...');
      const res = await fetch('https://r.jina.ai/' + clean, { headers: { Accept: 'text/plain' } });
      if (!res.ok) return '';
      const text = await res.text();
      setScrapeStatus('Analysing hospital information...');
      return text.slice(0, 3000);
    } catch { return ''; }
  }

  async function handleStart() {
    if (!validate()) return;
    setStep('scraping');

    const context = userData.hospitalWebsite.trim() ? await scrapeHospital(userData.hospitalWebsite) : '';
    setHospitalContext(context);
    setStep('connecting');

    // Wait up to 8s for VAPI module to assign window.Vapi
    let VapiClass = window.Vapi;
    if (!VapiClass) {
      VapiClass = await new Promise(resolve => {
        const done = () => resolve(window.Vapi || null);
        window.addEventListener('vapi-ready', done, { once: true });
        setTimeout(done, 8000);
      });
    }
    if (!VapiClass) {
      setVapiError('Voice SDK failed to load. Please check your internet connection and try again.');
      setStep('lead');
      return;
    }

    const vapi = new VapiClass(VAPI_PUBLIC_KEY);
    vapiRef.current = vapi;

    vapi.on('call-start', () => {
      setStep('voice');
      setCallState('ai_speaking');
      setCallDuration(0);
      durationRef.current = setInterval(() => setCallDuration(d => d + 1), 1000);
    });

    vapi.on('speech-start', () => setCallState('ai_speaking'));
    vapi.on('speech-end',   () => setCallState('listening'));

    vapi.on('message', msg => {
      if (msg.type === 'transcript' && msg.role === 'assistant' && msg.transcriptType === 'final') {
        setAiText(msg.transcript);
      }
    });

    vapi.on('call-end', () => {
      clearInterval(durationRef.current);
      setStep('report');
    });

    vapi.on('error', err => {
      console.error('VAPI error:', err);
      clearInterval(durationRef.current);
      setVapiError('Connection issue. Showing your preliminary report.');
      setStep('report');
    });

    const firstName = userData.name.trim().split(' ')[0];
    const firstMsg  = context
      ? `Hello ${firstName}! I am Dr. Priya, an N.A.B.H. accreditation consultant at A.H.C. Consulting. I have had a chance to review ${userData.hospitalName}'s website and have some context about your services. I will be conducting a brief N.A.B.H. readiness assessment — it should take about 5 minutes. To start, how many beds does ${userData.hospitalName} have, and what level of care do you primarily provide?`
      : `Hello ${firstName}! I am Dr. Priya, an N.A.B.H. accreditation consultant at A.H.C. Consulting. I will be conducting a brief N.A.B.H. readiness assessment for ${userData.hospitalName} — it should take about 5 minutes. To start, how many beds does your hospital have, and what level of care do you primarily provide — primary, secondary, or tertiary?`;

    try {
      await vapi.start({
        transcriber: { provider: 'deepgram', model: 'nova-2', language: 'en-IN' },
        model: {
          provider: 'openai',
          model: 'gpt-4o-mini',
          messages: [{ role: 'system', content: buildNabhSystemPrompt(userData, context) }],
          temperature: 0.65,
          maxTokens: 300
        },
        voice: { provider: 'azure', voiceId: 'en-IN-NeerjaNeural' },
        name: 'AHC Consulting NABH Assessment',
        firstMessage: firstMsg,
        endCallMessage: 'Thank you for your time. I strongly encourage you to reach out to the A.H.C. Consulting team for an in-person N.A.B.H. gap assessment. You can call Sneha at plus 91 86673 70744. Take care!',
        maxDurationSeconds: 600
      });
    } catch (err) {
      console.error('VAPI start error:', err);
      setVapiError('Could not connect. Showing your preliminary report.');
      setStep('report');
    }
  }

  function handleEndCall() {
    clearInterval(durationRef.current);
    if (vapiRef.current) { try { vapiRef.current.stop(); } catch (e) {} }
    setStep('report');
  }

  function formatDuration(s) {
    const m = Math.floor(s / 60), sec = s % 60;
    return `${String(m).padStart(2,'0')}:${String(sec).padStart(2,'0')}`;
  }

  // Score & categories (indicative — in production, derive from VAPI conversation analysis)
  const score = 32;
  const radius = 78; const C = Math.PI * radius; const filled = C * score / 100;
  const categories = [
    { name: 'Statutory Licences & Compliance', score: 25, color: '#d45656' },
    { name: 'OT Standards & Infrastructure',   score: 30, color: '#d45656' },
    { name: 'Staff Ratios & Credentialing',     score: 38, color: '#f59e0b' },
    { name: 'Medical Records & ICD-10 Coding',  score: 28, color: '#d45656' },
    { name: 'SOPs & Quality Management',        score: 20, color: '#d45656' },
    { name: 'Fire Safety & Facilities',         score: 42, color: '#f59e0b' },
  ];

  const inputBase = { width: '100%', height: 44, background: '#fff', color: '#0a1628', border: '1.5px solid #d0e4f8', borderRadius: 8, padding: '10px 14px', font: '400 15px var(--font-sans)', outline: 'none', boxSizing: 'border-box' };

  return (
    <div onClick={e => e.target === e.currentTarget && onClose()} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(10,22,40,0.65)', backdropFilter: 'blur(6px)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div style={{ background: '#fff', borderRadius: 20, width: '100%', maxWidth: step === 'report' ? 700 : 520, maxHeight: '92vh', overflowY: 'auto', boxShadow: '0 40px 80px rgba(0,0,0,0.28)', position: 'relative', animation: 'ai-fade-in 0.25s ease' }}>

        {/* Close */}
        <button onClick={onClose} style={{ position: 'absolute', top: 16, right: 16, zIndex: 10, background: '#f0f4f8', border: 'none', borderRadius: 9999, width: 32, height: 32, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#5a6e82" strokeWidth="2.5" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>

        {/* ── LEAD FORM ── */}
        {step === 'lead' && (
          <div style={{ padding: 40 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
              <span style={{ width: 44, height: 44, borderRadius: 12, background: '#1565C0', flexShrink: 0, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                <MicSvg size={22} stroke="#fff" />
              </span>
              <div>
                <div style={{ font: '700 18px var(--font-sans)', color: '#0a1628' }}>Free AI NABH Assessment</div>
                <div style={{ font: '400 13px var(--font-sans)', color: '#8898aa', marginTop: 2 }}>5 min · Voice conversation · Instant readiness report</div>
              </div>
            </div>

            {vapiError && (
              <div style={{ background: '#fdeaea', border: '1px solid #f5c6c6', borderRadius: 8, padding: '10px 14px', font: '400 13px var(--font-sans)', color: '#b03030', marginTop: 12 }}>{vapiError}</div>
            )}

            <p style={{ font: '400 14px var(--font-sans)', color: '#5a6e82', lineHeight: 1.7, margin: '18px 0 24px' }}>
              Our AI consultant Dr. Priya reviews your hospital's website, then conducts a structured NABH Initial Survey assessment to give you an instant readiness score and gap report — personalised to your hospital.
            </p>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
              {[{ key: 'name', label: 'Full Name', ph: 'Dr. / Mr. / Ms. Your Name', type: 'text' }, { key: 'mobile', label: 'Mobile Number', ph: 'Your 10-digit number', type: 'tel' }].map(f => (
                <div key={f.key}>
                  <label style={{ display: 'block', font: '600 12px var(--font-sans)', color: '#344a60', marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.5 }}>{f.label}</label>
                  <input type={f.type} placeholder={f.ph} value={userData[f.key]} onChange={e => setUserData({ ...userData, [f.key]: e.target.value })} style={{ ...inputBase, borderColor: errors[f.key] ? '#d45656' : '#d0e4f8' }} />
                  {errors[f.key] && <div style={{ font: '400 12px var(--font-sans)', color: '#d45656', marginTop: 4 }}>{errors[f.key]}</div>}
                </div>
              ))}
            </div>

            <div style={{ marginBottom: 14 }}>
              <label style={{ display: 'block', font: '600 12px var(--font-sans)', color: '#344a60', marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.5 }}>Email Address</label>
              <input type="email" placeholder="you@hospital.com" value={userData.email} onChange={e => setUserData({ ...userData, email: e.target.value })} style={{ ...inputBase, borderColor: errors.email ? '#d45656' : '#d0e4f8' }} />
              {errors.email && <div style={{ font: '400 12px var(--font-sans)', color: '#d45656', marginTop: 4 }}>{errors.email}</div>}
            </div>

            <div style={{ borderTop: '1px solid #e8f0f8', paddingTop: 18, marginBottom: 14 }}>
              <div style={{ font: '600 12px var(--font-sans)', color: '#1565C0', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 14 }}>Hospital Details</div>
              <div style={{ marginBottom: 14 }}>
                <label style={{ display: 'block', font: '600 12px var(--font-sans)', color: '#344a60', marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.5 }}>Hospital Name</label>
                <input type="text" placeholder="e.g. Lifetron Multispecialty Hospital" value={userData.hospitalName} onChange={e => setUserData({ ...userData, hospitalName: e.target.value })} style={{ ...inputBase, borderColor: errors.hospitalName ? '#d45656' : '#d0e4f8' }} />
                {errors.hospitalName && <div style={{ font: '400 12px var(--font-sans)', color: '#d45656', marginTop: 4 }}>{errors.hospitalName}</div>}
              </div>
              <div>
                <label style={{ display: 'block', font: '600 12px var(--font-sans)', color: '#344a60', marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                  Hospital Website <span style={{ font: '400 11px var(--font-sans)', color: '#aaa', textTransform: 'none', letterSpacing: 0 }}>(optional — personalises your assessment)</span>
                </label>
                <input type="url" placeholder="www.yourhospital.com" value={userData.hospitalWebsite} onChange={e => setUserData({ ...userData, hospitalWebsite: e.target.value })} style={inputBase} />
                {userData.hospitalWebsite.trim() && (
                  <div style={{ font: '400 12px var(--font-sans)', color: '#1565C0', marginTop: 5, display: 'flex', alignItems: 'center', gap: 5 }}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>
                    Dr. Priya will review your website before the call
                  </div>
                )}
              </div>
            </div>

            <button onClick={handleStart} style={{ width: '100%', height: 52, marginTop: 6, background: '#1565C0', color: '#fff', border: 'none', borderRadius: 10, font: '700 15px var(--font-sans)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, boxShadow: '0 4px 16px rgba(21,101,192,0.35)' }}>
              <MicSvg size={18} stroke="#fff" />
              Start Free AI Assessment
            </button>
            <p style={{ font: '400 12px var(--font-sans)', color: '#c0c8d4', textAlign: 'center', marginTop: 14, lineHeight: 1.5 }}>
              Confidential. No data saved or shared. Allow microphone access when prompted.
            </p>
          </div>
        )}

        {/* ── SCRAPING ── */}
        {step === 'scraping' && (
          <div style={{ padding: '64px 40px', textAlign: 'center' }}>
            <div style={{ width: 72, height: 72, borderRadius: 9999, margin: '0 auto 24px', background: 'linear-gradient(135deg, #0E3F8A, #1565C0)', display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'ai-pulse 1.5s ease-in-out infinite' }}>
              <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
            </div>
            <div style={{ font: '700 20px var(--font-sans)', color: '#0a1628' }}>Analysing {userData.hospitalName}</div>
            <p style={{ font: '400 14px var(--font-sans)', color: '#8898aa', marginTop: 8, lineHeight: 1.6 }}>
              {scrapeStatus || (userData.hospitalWebsite ? 'Dr. Priya is reviewing your hospital website...' : 'Preparing your assessment session...')}
            </p>
            <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginTop: 24 }}>
              {[0,1,2].map(i => <div key={i} style={{ width: 8, height: 8, borderRadius: 9999, background: '#1565C0', animation: 'ai-dot 1.4s ease-in-out infinite', animationDelay: `${i * 0.2}s` }} />)}
            </div>
          </div>
        )}

        {/* ── CONNECTING ── */}
        {step === 'connecting' && (
          <div style={{ padding: '64px 40px', textAlign: 'center' }}>
            <div style={{ width: 72, height: 72, borderRadius: 9999, margin: '0 auto 24px', background: 'linear-gradient(135deg, #1565C0, #42A5F5)', display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'ai-pulse 1.5s ease-in-out infinite' }}>
              <MicSvg size={30} stroke="white" />
            </div>
            <div style={{ font: '700 20px var(--font-sans)', color: '#0a1628' }}>Connecting to Dr. Priya...</div>
            <p style={{ font: '400 14px var(--font-sans)', color: '#8898aa', marginTop: 8 }}>Please allow microphone access when your browser prompts</p>
            {hospitalContext && (
              <div style={{ marginTop: 16, display: 'inline-flex', alignItems: 'center', gap: 7, background: '#EBF4FF', border: '1px solid #b8d8f8', borderRadius: 9999, padding: '5px 14px', font: '500 13px var(--font-sans)', color: '#1565C0' }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>
                Website analysed — assessment personalised
              </div>
            )}
            <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginTop: 24 }}>
              {[0,1,2].map(i => <div key={i} style={{ width: 8, height: 8, borderRadius: 9999, background: '#1565C0', animation: 'ai-dot 1.4s ease-in-out infinite', animationDelay: `${i * 0.2}s` }} />)}
            </div>
          </div>
        )}

        {/* ── VOICE CALL ── */}
        {step === 'voice' && (
          <div style={{ padding: 36 }}>
            {/* Avatar + status */}
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <div style={{ position: 'relative', display: 'inline-block' }}>
                <div style={{ width: 80, height: 80, borderRadius: 9999, margin: '0 auto', background: 'linear-gradient(135deg, #0E3F8A, #1565C0)', display: 'flex', alignItems: 'center', justifyContent: 'center', ...(callState === 'ai_speaking' ? { animation: 'ai-pulse 1.2s ease-in-out infinite' } : {}) }}>
                  <svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.5"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                </div>
                <div style={{ position: 'absolute', bottom: 2, right: 2, width: 18, height: 18, borderRadius: 9999, background: callState === 'listening' ? '#d45656' : '#22c55e', border: '2px solid #fff', animation: 'ai-pulse 1s ease-in-out infinite' }} />
              </div>
              <div style={{ font: '700 17px var(--font-sans)', color: '#0a1628', marginTop: 12 }}>Dr. Priya · AHC Consulting</div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginTop: 4 }}>
                <div style={{ font: '400 13px var(--font-sans)', color: callState === 'listening' ? '#d45656' : '#8898aa' }}>
                  {callState === 'ai_speaking' ? '● Speaking' : callState === 'listening' ? '⬤ Listening...' : '◌ Processing...'}
                </div>
                <div style={{ font: '500 12px var(--font-mono)', color: '#8898aa', background: '#f7f9fc', border: '1px solid #e0e7f0', borderRadius: 9999, padding: '2px 8px' }}>{formatDuration(callDuration)}</div>
              </div>
            </div>

            {/* Waveform */}
            <div style={{ background: '#0a1628', borderRadius: 16, padding: '18px 16px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 3, marginBottom: 20, height: 76, overflow: 'hidden' }}>
              {barHeights.map((h, i) => (
                <div key={i} style={{
                  width: 3, borderRadius: 2,
                  background: callState === 'listening' ? '#d45656' : callState === 'ai_speaking' ? '#42A5F5' : '#344a60',
                  height: callState === 'processing' ? '4px' : `${h}px`,
                  opacity: callState === 'processing' ? 0.3 : 1,
                  transition: 'height 0.3s ease, background 0.3s ease',
                  animation: callState !== 'processing' ? `ai-bar-wave ${0.6 + (i % 4) * 0.12}s ease-in-out infinite alternate` : 'none',
                  animationDelay: `${i * 0.04}s`
                }} />
              ))}
            </div>

            {/* Transcript bubble */}
            {aiText && (
              <div style={{ background: '#EBF4FF', border: '1px solid #b8d8f8', borderRadius: 12, padding: '14px 18px', marginBottom: 20, font: '400 15px var(--font-sans)', color: '#0E3F8A', lineHeight: 1.65 }}>
                <div style={{ font: '600 11px var(--font-sans)', color: '#1565C0', textTransform: 'uppercase', letterSpacing: 0.8, marginBottom: 6 }}>Dr. Priya</div>
                {aiText}
              </div>
            )}

            {/* Listening indicator */}
            {callState === 'listening' && (
              <div style={{ background: '#fff3f3', border: '1px solid #fecdd3', borderRadius: 10, padding: '12px 16px', textAlign: 'center', marginBottom: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
                <div style={{ width: 9, height: 9, borderRadius: 9999, background: '#d45656', animation: 'ai-pulse 0.9s ease-in-out infinite' }} />
                <span style={{ font: '600 14px var(--font-sans)', color: '#b03030' }}>Your turn — please speak now</span>
              </div>
            )}

            {/* End call */}
            <button onClick={handleEndCall} style={{ width: '100%', height: 46, background: '#fdeaea', color: '#b03030', border: '1px solid #fecdd3', borderRadius: 10, font: '600 14px var(--font-sans)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45c.94.34 1.94.58 2.95.72A2 2 0 0 1 22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.42 19.42 0 0 1 4.69 12 19.79 19.79 0 0 1 1.61 3.18 2 2 0 0 1 3.6 1h3a2 2 0 0 1 2 1.72 12.05 12.05 0 0 0 .72 2.95A2 2 0 0 1 8.87 7.8l-1.27 1.27a16 16 0 0 0 3.08 4.24z"/>
              </svg>
              End Call &amp; View My Report
            </button>
          </div>
        )}

        {/* ── REPORT ── */}
        {step === 'report' && (
          <div style={{ padding: 40 }}>
            <div style={{ textAlign: 'center', marginBottom: 28 }}>
              <div style={{ font: '600 11px var(--font-sans)', color: '#1565C0', letterSpacing: 1, textTransform: 'uppercase' }}>Assessment Complete</div>
              <h2 style={{ font: '700 26px var(--font-sans)', color: '#0a1628', letterSpacing: '-0.5px', margin: '10px 0 0' }}>Your NABH Readiness Report</h2>
              <p style={{ font: '400 14px var(--font-sans)', color: '#8898aa', marginTop: 6 }}>
                {userData.hospitalName} · Preliminary AI Assessment
              </p>
            </div>

            {/* Gauge */}
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <svg width="210" height="115" viewBox="-5 -10 210 115">
                <path d={`M 10 95 A ${radius} ${radius} 0 0 1 ${10 + 2 * radius} 95`} fill="none" stroke="#e0e7f0" strokeWidth="14" strokeLinecap="round"/>
                <path d={`M 10 95 A ${radius} ${radius} 0 0 1 ${10 + 2 * radius} 95`} fill="none" stroke="#1565C0" strokeWidth="14" strokeLinecap="round" strokeDasharray={`${filled} ${C}`}/>
                <text x="105" y="82" textAnchor="middle" fontSize="46" fontWeight="700" fontFamily="'Geist Mono','Courier New',monospace" fill="#0a1628">{score}</text>
                <text x="105" y="98" textAnchor="middle" fontSize="13" fontFamily="var(--font-sans)" fill="#8898aa">out of 100</text>
              </svg>
              <div style={{ display: 'inline-block', marginTop: 4, background: '#fef3c7', color: '#92400e', borderRadius: 9999, padding: '4px 16px', font: '600 11px var(--font-sans)', letterSpacing: 0.5, textTransform: 'uppercase' }}>Low Readiness — Action Required</div>
            </div>

            {/* Sections */}
            <div style={{ marginBottom: 24 }}>
              <div style={{ font: '700 14px var(--font-sans)', color: '#0a1628', marginBottom: 14 }}>NABH Domain Scores</div>
              {categories.map(cat => (
                <div key={cat.name} style={{ marginBottom: 13 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
                    <span style={{ font: '400 13px var(--font-sans)', color: '#344a60' }}>{cat.name}</span>
                    <span style={{ font: '700 13px var(--font-sans)', color: cat.color }}>{cat.score}%</span>
                  </div>
                  <div style={{ height: 7, background: '#e8f0f8', borderRadius: 9999, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${cat.score}%`, background: cat.color, borderRadius: 9999 }} />
                  </div>
                </div>
              ))}
            </div>

            {/* Key finding */}
            <div style={{ background: '#fff8e6', border: '1px solid #fcd34d', borderRadius: 12, padding: 18, marginBottom: 20 }}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#d97706" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 2 }}>
                  <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
                  <line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>
                </svg>
                <div style={{ font: '400 14px var(--font-sans)', color: '#92400e', lineHeight: 1.7 }}>
                  Multiple domains show Major Non-Conformity risk. Statutory licence gaps, OT infrastructure deficiencies, and missing quality management systems would each individually prevent NABH certification. Without expert guidance, achieving accreditation independently is very unlikely.
                </div>
              </div>
            </div>

            {/* Revenue impact box */}
            <div style={{ background: '#EBF4FF', border: '1px solid #b8d8f8', borderRadius: 12, padding: 18, marginBottom: 24 }}>
              <div style={{ font: '700 14px var(--font-sans)', color: '#0E3F8A', marginBottom: 10 }}>What this is costing you every month</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {[
                  ['indian-rupee', '10% less on every PMJAY claim you process'],
                  ['x-circle', 'Insurance empanelment applications rejected or delayed'],
                  ['users', 'Patients choosing NABH-certified competitors over you'],
                ].map(([icon, text]) => (
                  <div key={text} style={{ display: 'flex', alignItems: 'center', gap: 10, font: '400 13.5px var(--font-sans)', color: '#1565C0' }}>
                    <Icon name={icon} size={14} color="#1565C0" />{text}
                  </div>
                ))}
              </div>
            </div>

            {/* Disclaimer */}
            <div style={{ background: '#f7f9fc', borderRadius: 10, padding: '12px 16px', marginBottom: 24, font: '400 12px var(--font-sans)', color: '#8898aa', lineHeight: 1.6 }}>
              <strong style={{ color: '#5a6e82' }}>Note:</strong> This is a preliminary AI-driven assessment based on your conversation. Scores are indicative. This data is not saved or shared. For a precise, department-by-department assessment, our team will visit your hospital in person.
            </div>

            {/* CTA */}
            <div style={{ background: 'linear-gradient(135deg, #0E3F8A 0%, #1565C0 100%)', borderRadius: 16, padding: 28, textAlign: 'center' }}>
              <div style={{ font: '700 18px var(--font-sans)', color: '#fff', marginBottom: 8 }}>Book your free in-person gap assessment</div>
              <p style={{ font: '400 13px var(--font-sans)', color: 'rgba(255,255,255,0.78)', lineHeight: 1.7, marginBottom: 24 }}>
                Our consultants will visit {userData.hospitalName || 'your hospital'}, assess every department against NABH standards, and give you a precise gap report — with a fixed timeline and certified outcome guaranteed.
              </p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <a href="tel:+918667370744" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, background: '#fff', color: '#1565C0', borderRadius: 10, padding: '14px 20px', font: '700 14px var(--font-sans)', textDecoration: 'none' }}>
                  <Icon name="phone" size={16} color="#1565C0" />
                  Call Sneha: +91 86673 70744
                </a>
                <a href="#contact" onClick={onClose} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, background: 'rgba(255,255,255,0.12)', color: '#fff', border: '1px solid rgba(255,255,255,0.25)', borderRadius: 10, padding: '12px 20px', font: '600 14px var(--font-sans)', textDecoration: 'none' }}>
                  Fill Contact Form
                </a>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  PrimaryPill, AccentPill, SecondaryPill, BluePill, OutlinePill,
  Icon, MintCheck, Container, SectionLabel, MicSvg,
  NabhNav, NabhFooter, AIAssessmentModal
});
