// Cancer Types & Identification Guide — ported from main project
// (frontend/components/cancer-types-guide.tsx). Data lives in
// cancer_types_data.js so both apps stay in sync from one source.
//
// View states:
//   • grid  — searchable card grid (default, what user landed on)
//   • detail — full reference for one cancer type (clicked "View Full Guide")

const _CG = window;

// Lucide-style line icons mapped from the data's icon name strings.
const _CGIcon = ({ d, size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
    {typeof d === 'string' ? <path d={d}/> : d}
  </svg>
);
const ICON_MAP = {
  heart:        <path d="M20.84 4.6a5.5 5.5 0 0 0-7.78-.04L12 5.5l-1.06-.94a5.5 5.5 0 0 0-7.78 7.78L12 21l8.84-8.66a5.5 5.5 0 0 0 0-7.74z"/>,
  wind:         <path d="M9.59 4.59A2 2 0 1 1 11 8H2m10.59 11.41A2 2 0 1 0 14 16H2m15.73-8.27A2.5 2.5 0 1 1 19.5 12H2"/>,
  activity:     <path d="M22 12h-4l-3 9L9 3l-3 9H2"/>,
  shield:       <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>,
  droplets:     <><path d="M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z"/><path d="M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97"/></>,
  dna:          <><path d="M2 15c6.667-6 13.333 0 20-6"/><path d="M9 22c1.798-1.998 2.518-3.995 2.807-5.993"/><path d="M15 2c-1.798 1.998-2.518 3.995-2.807 5.993"/><path d="m17 6-2.5-2.5"/><path d="m14 8-1-1"/><path d="m7 18 2.5 2.5"/><path d="m3.5 14.5.5.5"/><path d="m20 9 .5.5"/><path d="m6.5 12.5 1 1"/><path d="m16.5 10.5 1 1"/><path d="m10 16 1.5 1.5"/></>,
  brain:        <><path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96.44A2.5 2.5 0 0 1 4 17.5v-1A2.5 2.5 0 0 1 2 14a2.5 2.5 0 0 1 2-2.45A2.5 2.5 0 0 1 4 9V8a2.5 2.5 0 0 1 3.04-2.44A2.5 2.5 0 0 1 9.5 2z"/><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96.44A2.5 2.5 0 0 0 20 17.5v-1A2.5 2.5 0 0 0 22 14a2.5 2.5 0 0 0-2-2.45A2.5 2.5 0 0 0 20 9V8a2.5 2.5 0 0 0-3.04-2.44A2.5 2.5 0 0 0 14.5 2z"/></>,
  eye:          <><circle cx="12" cy="12" r="3"/><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"/></>,
  bone:         <path d="M17 10c.7-.7 1.69 0 2.5 0a2.5 2.5 0 1 0 0-5 .5.5 0 0 1-.5-.5 2.5 2.5 0 1 0-5 0c0 .81.7 1.8 0 2.5l-7 7c-.7.7-1.69 0-2.5 0a2.5 2.5 0 0 0 0 5c.28 0 .5.22.5.5a2.5 2.5 0 1 0 5 0c0-.81-.7-1.8 0-2.5z"/>,
  baby:         <><path d="M9 12h.01"/><path d="M15 12h.01"/><path d="M10 16c.5.3 1.2.5 2 .5s1.5-.2 2-.5"/><path d="M19 6.3a9 9 0 0 1 1.8 3.9 2 2 0 0 1 0 3.6 9 9 0 0 1-17.6 0 2 2 0 0 1 0-3.6A9 9 0 0 1 12 3c2 0 3.5 1.1 3.5 2.5s-.9 2.5-2 2.5c-.8 0-1.5-.4-1.5-1"/></>,
  pill:         <><path d="M10.5 20.5 20 11a4.95 4.95 0 1 0-7-7L3.5 13.5a4.95 4.95 0 1 0 7 7Z"/><path d="m8.5 8.5 7 7"/></>,
  syringe:      <><path d="m18 2 4 4"/><path d="m17 7 3-3"/><path d="M19 9 8.7 19.3c-1 1-2.5 1-3.4 0l-.6-.6c-1-1-1-2.5 0-3.4L15 5"/><path d="m9 11 4 4"/><path d="m5 19-3 3"/><path d="m14 4 6 6"/></>,
  microscope:   <><path d="M6 18h8"/><path d="M3 22h18"/><path d="M14 22a7 7 0 1 0 0-14h-1"/><path d="M9 14h2"/><path d="M9 12a2 2 0 0 1-2-2V6h6v4a2 2 0 0 1-2 2Z"/><path d="M12 6V3a1 1 0 0 0-1-1H9a1 1 0 0 0-1 1v3"/></>,
  stethoscope:  <><path d="M11 2v2"/><path d="M5 2v2"/><path d="M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1"/><path d="M8 15a6 6 0 0 0 12 0v-3"/><circle cx="20" cy="10" r="2"/></>,
  target:       <><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></>,
  radiation:    <><circle cx="12" cy="12" r="2"/><path d="M12 2v4"/><path d="M12 18v4"/><path d="m4.93 4.93 2.83 2.83"/><path d="m16.24 16.24 2.83 2.83"/><path d="M2 12h4"/><path d="M18 12h4"/><path d="m4.93 19.07 2.83-2.83"/><path d="m16.24 7.76 2.83-2.83"/></>,
  trendingup:   <><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></>,
  filetext:     <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></>,
  bookopen:     <><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></>,
  users:        <><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></>,
  // Generic fallback so unknown icon names still render something
  __default:    <circle cx="12" cy="12" r="9"/>,
};
const _CGIconByName = ({ name, size = 24 }) => {
  const d = ICON_MAP[(name || '').toLowerCase()] || ICON_MAP.__default;
  return <_CGIcon d={d} size={size}/>;
};

// ─── Detail view ─────────────────────────────────────────────────────────────
const _CGDetail = ({ ct, onBack }) => {
  const t = window.useLanguage().t;
  const Section = ({ title, children }) => (
    <div className="cg-section">
      <div className="cg-section-title">{t(title)}</div>
      <div className="cg-section-body">{children}</div>
    </div>
  );
  return (
    <div className="cg-detail">
      <div className="cg-detail-head" style={{borderColor: ct.color}}>
        <button className="btn ghost sm" onClick={onBack}>← {t('Back')}</button>
        <div className="cg-detail-title-wrap">
          <div className="cg-icon-square" style={{background: ct.color}}>
            <_CGIconByName name={ct.icon} size={28}/>
          </div>
          <div>
            <h1 style={{margin:0}}>{ct.name}</h1>
            <div style={{color: ct.color, fontWeight:600, fontSize:17, marginTop:2}}>{ct.category}</div>
          </div>
        </div>
      </div>

      <div className="cg-detail-grid">
        <div className="cg-stat">
          <div className="cg-stat-label">{t('Prevalence')}</div>
          <div>{ct.prevalence}</div>
        </div>
        <div className="cg-stat">
          <div className="cg-stat-label">{t('Survival Rate')}</div>
          <div>{ct.survival_rate}</div>
        </div>
      </div>

      <Section title="Overview"><p>{ct.overview}</p></Section>

      {ct.subtypes?.length > 0 && (
        <Section title="Subtypes">
          <ul>{ct.subtypes.map((s, i) => <li key={i}>{s}</li>)}</ul>
        </Section>
      )}

      {ct.risk_factors?.length > 0 && (
        <Section title="Risk Factors">
          <div className="cg-chips">{ct.risk_factors.map((s, i) => <span key={i} className="cg-chip">{s}</span>)}</div>
        </Section>
      )}

      <div className="cg-two-col">
        {ct.early_symptoms?.length > 0 && (
          <Section title="Early Symptoms">
            <ul>{ct.early_symptoms.map((s, i) => <li key={i}>{s}</li>)}</ul>
          </Section>
        )}
        {ct.advanced_symptoms?.length > 0 && (
          <Section title="Advanced Symptoms">
            <ul>{ct.advanced_symptoms.map((s, i) => <li key={i}>{s}</li>)}</ul>
          </Section>
        )}
      </div>

      {ct.screening_methods?.length > 0 && (
        <Section title="Screening Methods">
          <ul>{ct.screening_methods.map((s, i) => <li key={i}>{s}</li>)}</ul>
        </Section>
      )}

      {ct.diagnostic_tests?.length > 0 && (
        <Section title="Diagnostic Tests">
          <table className="cg-table">
            <thead><tr><th>{t('Test')}</th><th>{t('Purpose')}</th><th>{t('When')}</th></tr></thead>
            <tbody>
              {ct.diagnostic_tests.map((d, i) => (
                <tr key={i}><td><b>{d.test}</b></td><td>{d.purpose}</td><td>{d.when}</td></tr>
              ))}
            </tbody>
          </table>
        </Section>
      )}

      {ct.biomarkers?.length > 0 && (
        <Section title="Biomarkers">
          <table className="cg-table">
            <thead><tr><th>{t('Marker')}</th><th>{t('Significance')}</th><th>{t('Actionable')}</th></tr></thead>
            <tbody>
              {ct.biomarkers.map((b, i) => (
                <tr key={i}>
                  <td><b className="mono">{b.marker}</b></td>
                  <td>{b.significance}</td>
                  <td>{b.actionable
                    ? <span style={{color:'#22c55e', fontWeight:600}}>● {t('Yes')}</span>
                    : <span style={{color:'var(--fg-3)'}}>—</span>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Section>
      )}

      {ct.staging?.length > 0 && (
        <Section title="Staging & Treatment Approach">
          <table className="cg-table">
            <thead><tr><th>{t('Stage')}</th><th>{t('Description')}</th><th>{t('Treatment Approach')}</th></tr></thead>
            <tbody>
              {ct.staging.map((s, i) => (
                <tr key={i}><td><b>{s.stage}</b></td><td>{s.description}</td><td>{s.treatment_approach}</td></tr>
              ))}
            </tbody>
          </table>
        </Section>
      )}

      {ct.treatment_options?.length > 0 && (
        <Section title="Treatment Options">
          <div className="cg-chips">{ct.treatment_options.map((s, i) => <span key={i} className="cg-chip cg-chip-tx">{s}</span>)}</div>
        </Section>
      )}

      {ct.key_mutations?.length > 0 && (
        <Section title="Key Mutations">
          <div className="cg-chips">{ct.key_mutations.map((s, i) => <span key={i} className="cg-chip cg-chip-mut">{s}</span>)}</div>
        </Section>
      )}

      {ct.prevention?.length > 0 && (
        <Section title="Prevention">
          <ul>{ct.prevention.map((s, i) => <li key={i}>{s}</li>)}</ul>
        </Section>
      )}
    </div>
  );
};

// ─── Grid view ───────────────────────────────────────────────────────────────
const CancerGuide = () => {
  const t = window.useLanguage().t;
  const [q, setQ] = React.useState('');
  const [active, setActive] = React.useState(null);  // currently-detailed cancer object
  const data = window.CANCER_TYPES || [];

  const filtered = React.useMemo(() => {
    if (!q.trim()) return data;
    const needle = q.toLowerCase();
    return data.filter(c => {
      const haystack = [
        c.name, c.category, c.overview,
        ...(c.key_mutations || []),
        ...(c.subtypes || []),
        ...(c.biomarkers || []).map(b => b.marker),
      ].join(' ').toLowerCase();
      return haystack.includes(needle);
    });
  }, [q, data]);

  if (active) return <_CGDetail ct={active} onBack={() => setActive(null)}/>;

  return (
    <div className="cancer-guide">
      <div className="cg-banner">
        <div className="cg-banner-icon"><_CGIconByName name="bookopen" size={26}/></div>
        <div>
          <h1 style={{margin:0, fontSize:26}}>{t('Cancer Types & Identification Guide')}</h1>
          <div style={{color:'var(--fg-3)', fontSize:17, marginTop:4}}>
            {t('End-to-end reference: symptoms, diagnosis, biomarkers, staging, treatment')}
          </div>
        </div>
      </div>

      <div className="cg-search-wrap">
        <input
          className="cg-search"
          type="text"
          placeholder={t('Search cancer types (e.g., breast, lung, EGFR, adenocarcinoma…)')}
          value={q}
          onChange={(e) => setQ(e.target.value)}
        />
      </div>

      <div className="cg-grid">
        {filtered.map(ct => (
          <div key={ct.id} className="cg-card" style={{borderTopColor: ct.color}} onClick={() => setActive(ct)}>
            <div className="cg-card-head">
              <div className="cg-icon-square" style={{background: ct.color}}>
                <_CGIconByName name={ct.icon} size={22}/>
              </div>
              {ct.biomarkers?.length > 0 && (
                <span className="cg-pill">{ct.biomarkers.length} {t('Biomarkers')}</span>
              )}
            </div>
            <h3 style={{margin:'14px 0 4px', fontSize:20}}>{ct.name}</h3>
            <div style={{color: ct.color, fontWeight:600, fontSize:16, marginBottom:8}}>{ct.category}</div>
            <p style={{fontSize:16, color:'var(--fg-3)', lineHeight:1.5, margin:'0 0 12px',
                       display:'-webkit-box', WebkitLineClamp:4, WebkitBoxOrient:'vertical', overflow:'hidden'}}>
              {ct.overview}
            </p>
            <div className="cg-card-stats">
              <div className="cg-card-stat">
                <div className="cg-card-stat-label">{t('Subtypes')}</div>
                <div className="cg-card-stat-value">{ct.subtypes?.length ?? 0}</div>
              </div>
              <div className="cg-card-stat">
                <div className="cg-card-stat-label">{t('Key Genes')}</div>
                <div className="cg-card-stat-value">{ct.key_mutations?.length ?? 0}</div>
              </div>
            </div>
            <button className="cg-card-link" style={{color: ct.color}}>
              {t('View Full Guide')} ›
            </button>
          </div>
        ))}
      </div>

      {filtered.length === 0 && (
        <div style={{textAlign:'center', padding:40, color:'var(--fg-3)'}}>{t('No matches.')}</div>
      )}
    </div>
  );
};

window.CancerGuide = CancerGuide;
