// Marketplace.jsx — 3-tab in-SPA marketplace
// Tabs: Patient Products / CE Training / Marketing Packages
// ZIP3 exclusivity note for marketing tier. VPS compliance copy. Pickaxe for payments.
// Compliance: AB 3030, no star ratings, no paid placement as quality signal.

const { useState } = React;

const AB3030 = 'AI-assisted content is disclosed under California AB 3030. Information only — not clinical advice.';

function openPickaxePayment(embedKey, title, desc) {
  if (window.PickaxeEmbeds?.openEmbed?.(embedKey, title, desc)) return true;
  if (window.PickaxeEmbeds?.showEmailFallback) {
    window.PickaxeEmbeds.showEmailFallback(title, desc);
    return true;
  }
  return false;
}

const PATIENT_PRODUCTS = [
  { id: 1, name: 'Oral Hygiene Starter Kit', desc: 'Electric brush, water flosser, tongue scraper — dentist-curated bundle.', price: 89, badge: 'Patient Favorite', img: '🪥' },
  { id: 2, name: 'Whitening System — Professional Grade', desc: 'Carbamide peroxide 10% with custom-fit trays (requires dentist script).', price: 129, badge: 'Compliance Note', img: '✨' },
  { id: 3, name: 'Night Guard — Mail-fit Kit', desc: 'Impressions sent to lab; guard delivered to home. For bruxism prevention.', price: 199, badge: 'Most Popular', img: '🦷' },
  { id: 4, name: 'SmileSim Preview Credit', desc: 'One AI-assisted smile simulation — informational preview, not a clinical prediction.', price: 15, badge: 'Digital', img: '📸' },
  { id: 5, name: 'Sensitivity Relief Toothpaste Duo', desc: 'Potassium nitrate formula — ADA-accepted for daily use between visits.', price: 24, badge: 'OTC', img: '🧴' },
  { id: 6, name: 'Interdental Brush Set', desc: 'Sized brushes for braces, bridges, and tight contacts — 8-pack.', price: 18, badge: 'OTC', img: '🪥' },
  { id: 7, name: 'Fluoride Rinse — Family Size', desc: 'Alcohol-free rinse for cavity prevention; child-safe when used as directed.', price: 14, badge: 'OTC', img: '💧' },
  { id: 8, name: 'Post-Op Care Bundle', desc: 'Soft brush, salt rinse, gauze, and recovery instructions card after extractions.', price: 32, badge: 'Recovery', img: '🩹' },
];

const MARKETING_TIERS = [
  {
    slug: 'starter',
    name: 'Local Visibility',
    price: 149,
    period: '/month',
    features: [
      'Verified listing on thedentist.ai',
      'ZIP3-exclusive placement (first-come)',
      'VPS score published publicly',
      'Monthly performance report',
    ],
    note: 'Payment does not influence VPS or recognition. Rankings remain payment-independent.',
  },
  {
    slug: 'growth',
    name: 'Growth Bundle',
    price: 399,
    period: '/month',
    popular: true,
    features: [
      'Everything in Local Visibility',
      'Priority in search results (alphabetical tiebreak only)',
      'Monthly patient newsletter feature',
      'Doctor profile page (photos, bio, CE)',
      'CE transcript + recognition display',
    ],
    note: 'ZIP3 exclusivity per specialty. VPS score remains independently calculated.',
  },
  {
    slug: 'pro',
    name: 'Practice Pro',
    price: 749,
    period: '/month',
    features: [
      'Everything in Growth Bundle',
      'SmileCam Pro widget embed on your site',
      'AI patient FAQ (AB 3030 compliant)',
      'Monthly reputation report',
      'Dedicated onboarding call',
    ],
    note: 'VPS and recognition earned only by performance data. Marketing spend is completely walled off.',
  },
  {
    slug: 'enterprise',
    name: 'DSO / Enterprise',
    price: 1499,
    period: '/month',
    features: [
      'All Practice Pro features × all locations',
      'Group dashboard + rollup VPS reporting',
      'Custom integration (PMS, booking)',
      'Quarterly strategy review',
    ],
    note: 'Contact for custom pricing on 10+ locations.',
  },
];

function ProductCard({ product }) {
  return (
    <div className="card session-product-row">
      <div className="session-product-emoji" aria-hidden="true">{product.img}</div>
      <div style={{ flex: 1 }}>
        <div className="session-row session-row--between">
          <div>
            <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2, color: 'var(--txt)' }}>{product.name}</div>
            <div className="session-muted" style={{ fontSize: 12, marginBottom: 6 }}>{product.desc}</div>
            {product.badge && <span className={`badge badge-${product.badge === 'Compliance Note' ? 'yellow' : 'blue'}`} style={{ fontSize: 11 }}>{product.badge}</span>}
          </div>
          <div style={{ textAlign: 'right', flexShrink: 0 }}>
            <div className="session-price">${product.price}</div>
            <button type="button" className="btn btn-primary btn-sm td-cta" style={{ marginTop: 6 }} aria-label={`Buy ${product.name}`}
              onClick={() => openPickaxePayment('marketing', `Purchase: ${product.name}`, `OTC product checkout — ${product.name} ($${product.price}).`) || openPickaxePayment('ce_enroll', `Purchase: ${product.name}`, `Product checkout — ${product.name}.`)}>
              Buy
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function MarketingTierCard({ tier }) {
  return (
    <div className={`card ${tier.popular ? 'card-highlighted' : ''}`}
      style={{
        borderColor: tier.popular ? 'var(--acc)' : undefined,
        borderWidth: tier.popular ? 2 : 1,
        position: 'relative',
      }}>
      {tier.popular && (
        <span className="badge badge-blue" style={{ position: 'absolute', top: -10, left: 16, fontSize: 11 }}>
          Most Popular
        </span>
      )}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
        <div>
          <div style={{ fontWeight: 700, fontSize: 15 }}>{tier.name}</div>
          <div className="session-text-xs" style={{ marginTop: 2 }}>ZIP3-exclusive per specialty</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <span style={{ fontWeight: 700, fontSize: 22, color: 'var(--acc)' }}>${tier.price}</span>
          <span className="session-muted" style={{ fontSize: 12 }}>{tier.period}</span>
        </div>
      </div>
      <ul style={{ paddingLeft: 0, margin: '0 0 12px', listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 6 }}>
        {tier.features.map((f, i) => (
          <li key={i} style={{ fontSize: 13, display: 'flex', gap: 8 }}>
            <span className="session-check" aria-hidden="true">✓</span>
            {f}
          </li>
        ))}
      </ul>
      <p className="session-footnote session-text-xs" style={{ marginBottom: 12, fontStyle: 'italic' }}>{tier.note}</p>
      <button type="button" className={`btn ${tier.popular ? 'btn-primary' : 'btn-secondary'} btn-block`}
        onClick={() => openPickaxePayment('marketing', `${tier.name} — Marketing Package`, `${tier.name} at $${tier.price}/mo. ZIP3 exclusivity applies. VPS recognition is never for sale.`)}>
        {tier.slug === 'enterprise' ? 'Contact Us' : 'Get Started →'}
      </button>
    </div>
  );
}

function Marketplace({ go }) {
  const [tab, setTab] = useState('patient');

  const tabs = [
    { slug: 'patient', label: '🛒 Patient Products' },
    { slug: 'ce', label: '🎓 CE Courses' },
    { slug: 'marketing', label: '📈 Marketing' },
  ];

  return (
    <div className="session-screen gap-screen animate-fade-in-up">
      <button type="button" className="btn btn-ghost btn-sm session-back" onClick={() => go?.('landing')} aria-label="Back to home">
        ← Home
      </button>
      <p className="session-eyebrow">VERIFIED · INDEPENDENT · NO PAID PLACEMENT</p>
      <h1 className="session-title">Marketplace</h1>
      <p className="section-subtitle session-subtitle" style={{ marginBottom: 20 }}>Products, CE training, and practice marketing — curated by TheDentist.ai.</p>

      <div className="session-tab-bar" role="tablist" aria-label="Marketplace sections">
        {tabs.map(t => (
          <button
            key={t.slug}
            type="button"
            role="tab"
            aria-selected={tab === t.slug}
            className={`session-tab-btn ${tab === t.slug ? 'is-active' : ''}`}
            onClick={() => setTab(t.slug)}
          >
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'patient' && (
        <div className="session-stack">
          <p className="session-muted" style={{ fontSize: 12 }}>
            Dentist-curated OTC products. No paid placement in rankings. <a href="/methodology/" className="methodology-link">Curation criteria →</a>
          </p>
          {PATIENT_PRODUCTS.map(p => <ProductCard key={p.id} product={p} />)}
        </div>
      )}

      {tab === 'ce' && (
        <div>
          {typeof CeHub === 'function' ? (
            <CeHub embedded />
          ) : (
            <button type="button" className="btn btn-secondary" onClick={() => go?.('ce-hub')}>
              View CE Hub →
            </button>
          )}
        </div>
      )}

      {tab === 'marketing' && (
        <div className="session-stack" style={{ gap: 16 }}>
          <div className="disclaimer-banner">
            <strong>VPS recognition is never for sale.</strong> Marketing spend has zero influence on Verified Performance Score, recognition tiers, or directory ranking. ZIP3 exclusivity is enforced per specialty. See{' '}
            <a href="/methodology/" className="methodology-link">methodology</a> for the independence guarantee.
          </div>
          {MARKETING_TIERS.map(t => <MarketingTierCard key={t.slug} tier={t} />)}
        </div>
      )}

      <div className="disclaimer-banner" style={{ marginTop: 24 }}>{AB3030}</div>
      <p className="session-footnote">TheDentist<em>.ai</em> · Smile Mentors Inc. · <a href="/methodology/" className="methodology-link" style={{ fontSize: 11 }}>Recognition methodology 2026.05</a></p>
    </div>
  );
}

window.Marketplace = Marketplace;
