// Shared components for the patient-web UI kit
const { useState, useEffect, useRef } = React;

// Lucide-style flat icon — accepts path data or icon name via FlatIcon
function Icon({ d, size = 20, stroke = 1.5, color, style, ...rest }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
      stroke={color || 'currentColor'}
      strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round"
      style={style} {...rest}
      dangerouslySetInnerHTML={{ __html: d }} />
  );
}

function FlatIcon({ name, size = 20, stroke = 1.75, color, style, className }) {
  const d = ICONS[name];
  if (!d) return null;
  return <Icon d={d} size={size} stroke={stroke} color={color} style={style} className={className ? 'fi ' + className : 'fi'} aria-hidden="true"/>;
}

const ICONS = (window.FlatIcons && window.FlatIcons.ICONS) ? window.FlatIcons.ICONS : {};

function Masthead({ lang, setLang, go }) {
  const [menuOpen, setMenuOpen] = useState(false);
  const [canNavigateBack, setCanNavigateBack] = useState(() => {
    const h = (typeof window !== 'undefined' && (window.location.hash || '').replace('#', '').trim()) || '';
    return !!h && h !== 'home';
  });
  const nav = (e, target) => {
    e.preventDefault();
    setMenuOpen(false);
    if (go) go(target);
  };
  const closeMenu = () => setMenuOpen(false);
  const browserBack = () => {
    closeMenu();
    if (typeof window.TDA_back === 'function') window.TDA_back();
    else window.history.back();
  };

  useEffect(() => {
    const updateBack = () => {
      const h = (window.location.hash || '').replace('#', '').trim();
      setCanNavigateBack(!!h && h !== 'home');
    };
    window.addEventListener('hashchange', updateBack);
    window.addEventListener('popstate', updateBack);
    updateBack();
    return () => {
      window.removeEventListener('hashchange', updateBack);
      window.removeEventListener('popstate', updateBack);
    };
  }, []);

  // Close on outside click
  useEffect(() => {
    if (!menuOpen) return;
    const handler = (e) => {
      if (!e.target.closest('.masthead') && !e.target.closest('.mobile-menu')) {
        setMenuOpen(false);
      }
    };
    document.addEventListener('click', handler);
    return () => document.removeEventListener('click', handler);
  }, [menuOpen]);

  return (
    <>
      <header className="masthead td-nav">
        <a className="brand" href="/#" onClick={(e)=>nav(e,'landing')} aria-label="TheDentist.ai home">
          <img src="./assets/logos/monogram-tooth-new.svg" width="34" height="34" alt=""/>
          <span className="wordmark td-wordmark">TheDentist<em className="ai">.ai</em></span>
        </a>
        <nav className="nav-links td-nav-links" aria-label="Primary">
          <a href="#audit-1" onClick={(e)=>nav(e,'audit-1')}>Smile Audit</a>
          <a href="#folio" onClick={(e)=>nav(e,'folio')}>SmileCam</a>
          <a href="#directory" onClick={(e)=>nav(e,'directory')}>Find a dentist</a>
          <a href="/education/">Videos</a>
          <a href="/cost/">Costs</a>
          <a href="/methodology/">Methodology</a>
        </nav>
        <div className="nav-right">
          {canNavigateBack && (
            <button type="button" className="btn btn-ghost btn-sm nav-back" onClick={browserBack} aria-label="Go back in browser history">
              <Icon d={ICONS.arrowL} size={16}/> Back
            </button>
          )}
          <LangToggle lang={lang} setLang={setLang}/>
          <a className="btn btn-ghost btn-sm" href="/portal/">Sign in</a>
          <Button variant="primary" size="sm" onClick={()=>{ closeMenu(); go && go('audit-1'); }}>Start audit</Button>
        </div>
        <button
          className={`hamburger${menuOpen?' open':''}`}
          aria-label="Toggle navigation"
          aria-expanded={menuOpen}
          onClick={()=>setMenuOpen(o=>!o)}
        >
          <span/><span/><span/>
        </button>
      </header>
      <div className={`mobile-menu${menuOpen?' open':''}`} aria-hidden={!menuOpen}>
        {canNavigateBack && (
          <button type="button" className="mm-link mm-back" onClick={browserBack}>
            ← Back
          </button>
        )}
        <button className="mm-link" onClick={(e)=>nav(e,'audit-1')}>Smile Audit</button>
        <button className="mm-link" onClick={(e)=>nav(e,'folio')}>SmileCam</button>
        <button className="mm-link" onClick={(e)=>nav(e,'directory')}>Find a dentist</button>
        <a className="mm-link" href="/cost/" onClick={closeMenu}>Costs</a>
        <a className="mm-link" href="/methodology/" onClick={closeMenu}>Methodology</a>
        <a className="mm-link" href="/education/" onClick={closeMenu}>Patient education</a>
        <a className="mm-link" href="/portal/" onClick={closeMenu} style={{borderTop:'1px solid var(--ink-5)', marginTop:8, paddingTop:14}}>Sign in</a>
        <div className="mm-cta">
          <LangToggle lang={lang} setLang={setLang}/>
          <Button variant="primary" size="md" onClick={(e)=>nav(e,'audit-1')}>Start your Smile Audit</Button>
        </div>
      </div>
    </>
  );
}

function LangToggle({ lang, setLang }) {
  return (
    <div className="lang-toggle" role="group" aria-label="Language">
      {['EN','ES','中文'].map(l => (
        <button key={l} className={lang===l?'active':''} onClick={()=>setLang(l)}>{l}</button>
      ))}
    </div>
  );
}

function Footer({ go }) {
  const link = (e, target) => { e.preventDefault(); if (go) go(target); };
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div className="footer-brand">
          <div style={{display:'flex',alignItems:'center',gap:10}}>
            <img src="./assets/logos/monogram-tooth-new.svg" width="28" height="28" alt=""/>
            <span className="wordmark td-wordmark" style={{fontSize:18}}>TheDentist<em className="ai">.ai</em></span>
          </div>
          <p className="t-meta" style={{maxWidth:300,marginTop:8}}>The Michelin Guide for dental care. Verified · Independent · No paid placement.</p>
        </div>
        <div className="footer-col">
          <div className="t-eyebrow">Get help</div>
          <a href="#audit-1" onClick={(e)=>link(e,'audit-1')}>Smile Audit</a>
          <a href="#folio" onClick={(e)=>link(e,'folio')}>SmileCam</a>
          <a href="#directory" onClick={(e)=>link(e,'directory')}>Find a dentist</a>
          <a href="/cost/">Costs in your ZIP</a>
          <a href="/education/">Patient education</a>
        </div>
        <div className="footer-col">
          <div className="t-eyebrow">How we work</div>
          <a href="/methodology/">Methodology</a>
          <a href="/council/">Benchmark Council</a>
          <a href="/privacy/">Privacy &amp; HIPAA</a>
        </div>
        <div className="footer-col">
          <div className="t-eyebrow">Smile Mentors</div>
          <a href="/jobs/">Jobs &amp; PRN</a>
          <a href="/marketplace/">Marketplace</a>
          <a href="/smile-mentors/">Careers home</a>
        </div>
        <div className="footer-col">
          <div className="t-eyebrow">Practitioners</div>
          <a href="/for-dentists/">About the program</a>
          <a href="#folio" onClick={(e)=>link(e,'folio')}>SmileCam Pro</a>
          <a href="/portal/">Sign in</a>
        </div>
      </div>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:12,flexWrap:'wrap',padding:'var(--s-3) 0 0',borderTop:'1px solid var(--ink-5)',marginTop:'var(--s-4)'}}>
        <button type="button" className="bc-link" style={{fontSize:12,background:'none',border:0,padding:0,cursor:'pointer',color:'var(--ink-3)'}} onClick={(e)=>{
          e.preventDefault();
          const onModern = (window.location.hash || '').replace('#','').toLowerCase() === 'modern';
          try { localStorage.setItem('td_view', onModern ? 'classic' : 'modern'); } catch{}
          window.location.hash = onModern ? '' : 'modern';
          window.location.reload();
        }}>{(typeof window !== 'undefined' && (window.location.hash || '').replace('#','').toLowerCase() === 'modern') ? '← Use classic home' : '↻ Try modern home (chooser + triage)'}</button>
        <span className="t-fine" style={{margin:0}}>Classic six-intent landing is the main site at /. Modern is optional (#modern).</span>
      </div>
      <div className="t-fine footer-disclosure">This is information, not diagnosis. A licensed dentist must confirm. AI-assisted content is generated under California AB 3030 disclosure and reviewed by the Benchmark Council under SB 1120 oversight.</div>
      <div className="t-meta footer-fine">© 2026 Smile Mentors Inc. · Reviewed by our Benchmark Council of licensed US dentists · Patient education & dental-assistant training available at <a href="/education/" style={{color:'var(--ink-3)'}}>thedentist.ai/education</a></div>
    </footer>
  );
}

function Breadcrumbs({ crumbs, go }) {
  return (
    <nav className="breadcrumbs" aria-label="Breadcrumb">
      {crumbs.map((c, i) => {
        const isLast = i === crumbs.length - 1;
        return (
          <React.Fragment key={i}>
            {i > 0 && <span className="bc-sep" aria-hidden="true">›</span>}
            {isLast
              ? <span className="bc-current">{c.label}</span>
              : c.screen
                ? <button className="bc-link" onClick={()=>go && go(c.screen)}>{c.label}</button>
                : <a className="bc-link" href={c.href||'#'}>{c.label}</a>
            }
          </React.Fragment>
        );
      })}
    </nav>
  );
}

function Button({ children, variant='primary', size='md', ...rest }) {
  return <button className={`btn btn-${variant} btn-${size}`} {...rest}>{children}</button>;
}

function Badge({ axis, tier, size = 64 }) {
  return <img src={`./assets/badges/${axis}--${tier}.svg`} width={size} height={size} alt={`${axis} ${tier}`}/>;
}

function Pill({ children, tone='neutral' }) {
  return <span className={`pill pill-${tone}`}>{children}</span>;
}

function ProgressDots({ step, total }) {
  return (
    <div className="dots" role="progressbar" aria-valuenow={step} aria-valuemax={total}>
      {Array.from({length:total},(_,i)=> <span key={i} className={i<step?'on':''}/>)}
    </div>
  );
}

function Disclosure() {
  return <p className="t-fine disclosure">This is information, not diagnosis. A licensed dentist must confirm.</p>;
}

Object.assign(window, { Icon, FlatIcon, ICONS, Masthead, LangToggle, Footer, Breadcrumbs, Button, Badge, Pill, ProgressDots, Disclosure });
