// PracticeDetail.jsx — Full practice profile screen (#practice-detail)
// Reads tda_selected_practice from localStorage (set by DirectoryCard openProfile).
// Compliance: AB 3030, VPS methodology link, positive-only recognition, no star ratings.

const { useState, useEffect } = React;

const AB3030 = 'AI-assisted content is disclosed under California AB 3030. This is information, not a clinical diagnosis — confirm with a licensed dentist.';

const R = window.RECOGNITION;

/** Directory API may send vps as a number or per-axis score map — never render the map in JSX. */
function numericVpsScore(practice) {
  if (!practice) return null;
  const raw = practice.overall_score ?? practice.vps_score ?? practice.vps;
  if (typeof raw === 'number' && !Number.isNaN(raw)) return Math.round(raw);
  if (typeof raw === 'string' && /^\d+(\.\d+)?$/.test(raw.trim())) return Math.round(Number(raw));
  if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
    const vals = Object.values(raw).map(Number).filter((n) => !Number.isNaN(n));
    if (vals.length) return Math.round(Math.max(...vals));
  }
  return null;
}

/** Canonical badges: [[axisSlug, tierSlug], …] from directory / Supabase / demo seed. */
function normalizeBadges(practice) {
  if (!practice) return [];
  if (Array.isArray(practice.badges) && practice.badges.length) {
    return practice.badges.filter((b) => Array.isArray(b) && b[0] && b[1]);
  }
  if (Array.isArray(practice.earned_axes) && practice.earned_axes.length) {
    return practice.earned_axes
      .filter((a) => a && a.axis && a.tier && a.tier !== 'listed')
      .map((a) => [a.axis, a.tier]);
  }
  return [];
}

/** Axis slugs only — array, or keys from a vps / axes object when badges are absent. */
function axisSlugsFromPractice(practice) {
  if (!practice) return [];
  const fromBadges = normalizeBadges(practice).map((b) => b[0]);
  if (fromBadges.length) return fromBadges;
  const axes = practice.recognition_axes ?? practice.axes;
  if (Array.isArray(axes)) return axes.filter((s) => typeof s === 'string');
  if (axes && typeof axes === 'object') return Object.keys(axes);
  const vpsMap = practice.vps;
  if (vpsMap && typeof vpsMap === 'object' && !Array.isArray(vpsMap)) return Object.keys(vpsMap);
  return [];
}

const SEED_SIMILAR = [
  { name: 'Sunrise Dental Group',    city: 'San Francisco, CA', vps: 78, specialty: 'General' },
  { name: 'Bay Area Family Dentistry', city: 'San Francisco, CA', vps: 74, specialty: 'General' },
  { name: 'Pacific Oral Care',       city: 'San Francisco, CA', vps: 71, specialty: 'General' },
];

function VPSDonut({ score }) {
  const n = typeof score === 'number' && !Number.isNaN(score) ? Math.round(score) : null;
  const r = 44;
  const circ = 2 * Math.PI * r;
  const filled = n != null ? (n / 100) * circ : 0;
  const color = n == null ? 'var(--color-text-tertiary,#9CA3AF)' : n >= 80 ? '#059669' : n >= 60 ? '#3b82f6' : '#d97706';
  const [shown, setShown] = useState(false);
  useEffect(() => { const t = setTimeout(() => setShown(true), 100); return () => clearTimeout(t); }, []);
  const dash = shown ? filled : 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
      <svg width={112} height={112} viewBox="0 0 112 112" aria-label={n != null ? `VPS score ${n} out of 100` : 'VPS score not yet published'}>
        <circle cx={56} cy={56} r={r} fill="none" stroke="var(--color-border,#E8EBF0)" strokeWidth={10}/>
        <circle
          cx={56} cy={56} r={r} fill="none"
          stroke={color} strokeWidth={10}
          strokeLinecap="round"
          strokeDasharray={`${dash} ${circ}`}
          strokeDashoffset={circ * 0.25}
          style={{ transition: 'stroke-dasharray 1.2s cubic-bezier(0.22,1,0.36,1)' }}
        />
        <text x={56} y={50} textAnchor="middle" dominantBaseline="middle"
          style={{ fontSize: 22, fontWeight: 700, fill: color, fontFeatureSettings: '"tnum"' }}>{n != null ? n : '—'}</text>
        <text x={56} y={68} textAnchor="middle" dominantBaseline="middle"
          style={{ fontSize: 10, fontWeight: 600, fill: 'var(--color-text-tertiary,#9CA3AF)', letterSpacing: '0.06em' }}>VPS</text>
      </svg>
      <a href="/methodology/" className="methodology-link" style={{ fontSize: 11 }}>
        Methodology 2026.05 →
      </a>
    </div>
  );
}

function RecognitionSection({ practice }) {
  const badges = normalizeBadges(practice);
  const items = badges.length
    ? badges
    : axisSlugsFromPractice(practice).map((axis) => [axis, 'recognized']);

  if (!items.length) return null;

  const axisLabel = (slug) => (R && R.axisShort ? R.axisShort(slug) : slug);
  const tierLabel = (tier) => (R && R.tierLabel ? R.tierLabel(tier) : tier);

  return (
    <div>
      <p style={{ fontSize: 12, color: 'var(--color-text-tertiary,#9CA3AF)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>
        Earned Recognition · {items.length} {items.length === 1 ? 'area' : 'areas'}
      </p>
      <div className="profile-axes" style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
        {items.map(([axis, tier]) => (
          <div className="profile-axis" key={axis} style={{ textAlign: 'center', minWidth: 88 }}>
            {typeof Badge === 'function'
              ? <Badge axis={axis} tier={tier} size={72} />
              : <span className="badge badge-blue" style={{ fontSize: 12, padding: '5px 12px', borderRadius: 99 }}>{axisLabel(axis)}</span>}
            <div style={{ fontSize: 13, fontWeight: 600, marginTop: 6 }}>{axisLabel(axis)}</div>
            <div className="t-tier" style={{ fontSize: 12, color: 'var(--color-text-secondary)' }}>{tierLabel(tier)}</div>
          </div>
        ))}
      </div>
      <p style={{ fontSize: 11, color: 'var(--color-text-tertiary)', marginTop: 12 }}>
        Positive-only recognition. Unearned axes are not shown. No paid placement as a quality signal.{' '}
        <a href="/methodology/" className="methodology-link">How we measure →</a>
      </p>
    </div>
  );
}

function InsurancePanel({ insurances }) {
  if (!insurances || !insurances.length) return (
    <p style={{ fontSize: 13, color: 'var(--color-text-tertiary)' }}>Insurance information not yet verified.</p>
  );
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
      {insurances.map((ins, i) => (
        <span key={i} className="badge badge-gray" style={{ fontSize: 12 }}>{ins}</span>
      ))}
    </div>
  );
}

function SimilarPracticeCard({ practice, go }) {
  return (
    <div
      className="card"
      style={{ cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 16px' }}
      onClick={() => {
        try { localStorage.setItem('tda_selected_practice', JSON.stringify(practice)); } catch (_) {}
        if (go) go('practice-detail');
      }}
      role="button"
      tabIndex={0}
      onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { try { localStorage.setItem('tda_selected_practice', JSON.stringify(practice)); } catch (_) {} if (go) go('practice-detail'); } }}
    >
      <div>
        <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--color-text-primary)' }}>{practice.name}</div>
        <div style={{ fontSize: 12, color: 'var(--color-text-tertiary)', marginTop: 2 }}>{practice.city}</div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontSize: 18, fontWeight: 700, color: '#059669', fontFeatureSettings: '"tnum"' }}>{numericVpsScore(practice) ?? '—'}</div>
        <div style={{ fontSize: 10, color: 'var(--color-text-tertiary)' }}>VPS</div>
      </div>
    </div>
  );
}

function PracticeDetail({ go, state }) {
  const [practice, setPractice] = useState(null);

  useEffect(() => {
    // Prefer state._selectedDentist (set by openProfile), fall back to localStorage
    const fromState = state && state._selectedDentist;
    if (fromState) { setPractice(fromState); return; }
    try {
      const raw = localStorage.getItem('tda_selected_practice');
      if (raw) setPractice(JSON.parse(raw));
    } catch (_) {}
  }, [state]);

  if (!practice) {
    return (
      <div className="screen-container gap-screen animate-fade-in-up">
        <button type="button" className="btn btn-ghost btn-sm" onClick={() => go?.('directory')} style={{ marginBottom: 16 }}>
          ← Find a dentist
        </button>
        <div className="disclaimer-banner">
          No practice selected. <button type="button" className="btn btn-ghost btn-sm" onClick={() => go?.('directory')}>Browse the directory →</button>
        </div>
      </div>
    );
  }

  const vps = numericVpsScore(practice) ?? 72;
  const insurances = practice.insurance || [];
  const languages = practice.languages || ['English'];
  const phone = practice.phone || practice.phone_number || null;
  const address = practice.address || practice.location || null;
  const accepting = practice.accepting !== false;

  return (
    <div className="gap-screen animate-fade-in-up" style={{ maxWidth: 720, margin: '0 auto', padding: '24px 16px 80px' }}>
      {/* Back */}
      <button type="button" className="btn btn-ghost btn-sm" onClick={() => go?.('directory')} style={{ marginBottom: 16, paddingLeft: 0 }}>
        ← Directory
      </button>

      {/* Eyebrow */}
      <p className="t-eyebrow" style={{ fontSize: 11, letterSpacing: '0.1em', color: 'var(--color-accent,#1A56DB)', fontWeight: 700, marginBottom: 8 }}>
        VERIFIED · INDEPENDENT · NO PAID PLACEMENT
      </p>

      {/* Header + VPS ring side-by-side */}
      <div style={{ display: 'flex', gap: 20, alignItems: 'flex-start', marginBottom: 24 }}>
        <div style={{ flex: 1 }}>
          <h1 style={{ fontSize: 'clamp(1.25rem,4vw,1.75rem)', fontWeight: 700, margin: '0 0 4px', letterSpacing: '-0.02em' }}>
            {practice.name}
          </h1>
          <p style={{ color: 'var(--color-text-secondary)', fontSize: 14, margin: 0 }}>
            {[practice.city || practice.address, practice.specialty || 'General Dentistry'].filter(Boolean).join(' · ')}
          </p>
          {accepting !== undefined && (
            <span className={accepting ? 'badge badge-green' : 'badge badge-yellow'} style={{ marginTop: 8, display: 'inline-flex' }}>
              {accepting ? '✓ Accepting new patients' : 'Waitlist only'}
            </span>
          )}
        </div>
        <VPSDonut score={vps} />
      </div>

      {/* Recognition — badges [[axis,tier],…] from /api/directory; vps may be a per-axis score map */}
      {normalizeBadges(practice).length > 0 || axisSlugsFromPractice(practice).length > 0 ? (
        <div className="card" style={{ marginBottom: 16 }}>
          <RecognitionSection practice={practice} />
        </div>
      ) : null}

      {/* Insurance */}
      <div className="card" style={{ marginBottom: 16 }}>
        <p style={{ fontSize: 12, color: 'var(--color-text-tertiary)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>
          Insurance Accepted
        </p>
        <InsurancePanel insurances={insurances} />
      </div>

      {/* Languages */}
      {languages.length > 0 && (
        <div className="card" style={{ marginBottom: 16 }}>
          <p style={{ fontSize: 12, color: 'var(--color-text-tertiary)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>
            Languages Spoken
          </p>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {languages.map((l, i) => (
              <span key={i} className="badge badge-gray" style={{ fontSize: 12 }}>{l}</span>
            ))}
          </div>
        </div>
      )}

      {/* Quick links */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 }}>
        <button
          type="button"
          className="card"
          style={{ textAlign: 'left', cursor: 'pointer', border: '1.5px solid var(--color-border)', background: 'var(--color-surface-raised)' }}
          onClick={() => go?.('cost-estimate')}
        >
          <div style={{ fontSize: 20, marginBottom: 4 }}>💵</div>
          <div style={{ fontWeight: 600, fontSize: 14 }}>Cost Estimate</div>
          <div style={{ fontSize: 12, color: 'var(--color-text-tertiary)' }}>Get transparent pricing →</div>
        </button>
        <button
          type="button"
          className="card"
          style={{ textAlign: 'left', cursor: 'pointer', border: '1.5px solid var(--color-border)', background: 'var(--color-surface-raised)' }}
          onClick={() => go?.('second-opinion')}
        >
          <div style={{ fontSize: 20, marginBottom: 4 }}>🔍</div>
          <div style={{ fontWeight: 600, fontSize: 14 }}>Second Opinion</div>
          <div style={{ fontSize: 12, color: 'var(--color-text-tertiary)' }}>Request a review →</div>
        </button>
      </div>

      {/* Similar practices */}
      <div style={{ marginBottom: 24 }}>
        <p style={{ fontSize: 12, color: 'var(--color-text-tertiary)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10 }}>
          Similar Practices
        </p>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {SEED_SIMILAR.map((p, i) => (
            <SimilarPracticeCard key={i} practice={p} go={go} />
          ))}
        </div>
      </div>

      {/* AB 3030 disclaimer */}
      <div className="disclaimer-banner" style={{ marginBottom: 12 }}>{AB3030}</div>

      <p style={{ fontSize: 11, color: 'var(--color-text-tertiary)', textAlign: 'center' }}>
        TheDentist<em style={{ fontStyle: 'italic' }}>.ai</em> · Smile Mentors Inc. ·{' '}
        <a href="/methodology/" className="methodology-link" style={{ fontSize: 11 }}>Recognition methodology 2026.05</a>
      </p>

      {/* Sticky booking bar (mobile) */}
      {(phone || address) && (
        <div style={{
          position: 'fixed', bottom: 0, left: 0, right: 0,
          background: 'var(--color-surface,#fff)', borderTop: '1px solid var(--color-border)',
          padding: '12px 16px', display: 'flex', gap: 10, zIndex: 100,
          boxShadow: '0 -4px 16px rgba(0,0,0,0.08)',
        }}>
          {phone && (
            <a href={`tel:${phone}`} className="btn btn-secondary" style={{ flex: 1 }}>📞 Call</a>
          )}
          <a
            href={address ? `https://maps.google.com/?q=${encodeURIComponent(address)}` : '#'}
            target="_blank" rel="noopener noreferrer"
            className="btn btn-secondary"
            style={{ flex: 1 }}
          >
            📍 Directions
          </a>
          <button type="button" className="btn btn-primary" style={{ flex: 2 }}
            onClick={() => go?.('forms')}>
            Book Appointment
          </button>
        </div>
      )}
    </div>
  );
}

window.PracticeDetail = PracticeDetail;
