// DecisionTree.jsx — Guided branching dental triage (information, not diagnosis)
// Five entry trees: Tooth Pain · Gum Issues · Cosmetic · Post-Op · Kid's Tooth
// Each walks 2–3 question nodes then renders a result with urgency + 3 categories + CTAs.
// Uses window.t(lang, key) from i18n.js.

const { useState } = React;

/* ── Tree data ────────────────────────────────────────────────────────────── */
// Node types: 'q' (question) | 'result'
// q:      { type:'q', text, sub?, options:[{label, next}] }
// result: { type:'result', urgency:'emergency'|'urgent'|'routine', title,
//           categories:[{name, desc}], note, guidance }

const TREES = {
  'tooth-pain': {
    label: 'Tooth pain or sensitivity',
    start: 'tp-1',
    nodes: {
      'tp-1': {
        type: 'q',
        text: 'How long has the pain been there?',
        options: [
          { label: 'Started today or yesterday',      next: 'tp-2a' },
          { label: 'Several days',                    next: 'tp-2b' },
          { label: 'A week or longer',                next: 'tp-result-persistent' },
          { label: "It comes and goes — I'm not sure", next: 'tp-2c' },
        ],
      },
      'tp-2a': {
        type: 'q',
        text: 'What does the pain feel like right now?',
        options: [
          { label: 'Sharp when I bite down',          next: 'tp-result-crack' },
          { label: 'Zings with cold or sweet',        next: 'tp-result-sensitivity' },
          { label: 'Throbbing — hard to ignore',      next: 'tp-result-pulpitis-irrev' },
          { label: 'Dull ache, hard to pinpoint',     next: 'tp-result-referred' },
        ],
      },
      'tp-2b': {
        type: 'q',
        text: 'Do you notice any swelling in your gum or face?',
        options: [
          { label: 'Yes — noticeable swelling',       next: 'tp-result-abscess' },
          { label: 'Gum looks a little puffy',        next: 'tp-result-perio' },
          { label: 'No swelling',                     next: 'tp-result-pulpitis-irrev' },
        ],
      },
      'tp-2c': {
        type: 'q',
        text: 'When does it most often flare up?',
        options: [
          { label: 'Cold drinks or air',              next: 'tp-result-sensitivity' },
          { label: 'Biting on something hard',        next: 'tp-result-crack' },
          { label: 'Randomly — no clear trigger',     next: 'tp-result-persistent' },
        ],
      },

      /* ── results ── */
      'tp-result-sensitivity': {
        type: 'result', urgency: 'routine',
        title: 'Tooth sensitivity — likely treatable',
        categories: [
          { name: 'Recession sensitivity', desc: 'Receding gums expose root surface, which has no enamel. Cold hits it directly. A desensitizing treatment or gum evaluation helps.' },
          { name: 'Early cavity', desc: 'A small cavity near the gumline or on the biting surface can cause cold sensitivity before it causes pain. Fillings are quick when caught early.' },
          { name: 'Reversible pulpitis', desc: 'Mild nerve inflammation — often from a recent filling or grinding — that resolves once the cause is removed.' },
        ],
        note: 'Sensitivity that has lasted more than 2–3 weeks, or that wakes you up, is worth seeing a dentist about soon.',
        guidance: 'routine',
      },
      'tp-result-crack': {
        type: 'result', urgency: 'urgent',
        title: 'Pain when biting — possible cracked tooth',
        categories: [
          { name: 'Cracked tooth syndrome', desc: 'A crack in the enamel or dentin opens under bite pressure, letting cold or force reach the nerve. A crown often stabilizes it before the nerve is involved.' },
          { name: 'Fractured cusp', desc: 'A chunk of tooth breaks off — often a back molar, especially with old silver fillings. Usually seen on an X-ray or by probing.' },
          { name: 'Split tooth', desc: 'A crack that runs through the tooth root. Caught early it may be saveable; caught late it may need extraction. Book soon.' },
        ],
        note: 'Biting pain that worsens over days is a sign the nerve may be getting involved. Sooner is better here.',
        guidance: 'urgent',
      },
      'tp-result-pulpitis-irrev': {
        type: 'result', urgency: 'urgent',
        title: 'Throbbing or constant pain — nerve may be involved',
        categories: [
          { name: 'Irreversible pulpitis', desc: 'The nerve inside the tooth is inflamed beyond what it can recover from. A root canal relieves the pain and saves the tooth — it is not as bad as its reputation.' },
          { name: 'Deep cavity reaching the nerve', desc: 'A cavity that has grown past enamel into dentin and reached the nerve chamber. Root canal or extraction are the typical options.' },
          { name: 'Cracked tooth (deep)', desc: 'A crack that extends to the pulp chamber. Depending on depth, a root canal plus crown or extraction may be recommended.' },
        ],
        note: 'Throbbing pain that is constant — not just with triggers — typically means the nerve is affected. This will not resolve on its own.',
        guidance: 'urgent',
      },
      'tp-result-abscess': {
        type: 'result', urgency: 'emergency',
        title: 'Swelling with pain — see a dentist today',
        categories: [
          { name: 'Dental abscess', desc: 'A pocket of infection around the tooth root or gum. It causes swelling, fever, and severe pain. Without treatment, infections can spread rapidly.' },
          { name: 'Periodontal abscess', desc: 'An abscess originating in the gum pocket rather than the tooth root. Often related to advanced gum disease.' },
          { name: 'Pericoronitis', desc: 'Infection around a partially erupted wisdom tooth. Swelling of the gum flap covering the tooth — common in teens and young adults.' },
        ],
        note: 'Facial swelling, fever, or difficulty swallowing are signs of a spreading infection. Call 911 or go to an emergency room if breathing or swallowing is affected.',
        guidance: 'emergency',
      },
      'tp-result-perio': {
        type: 'result', urgency: 'urgent',
        title: 'Gum tenderness — possible gum infection',
        categories: [
          { name: 'Localized gum infection', desc: 'Bacteria trapped under the gumline cause localized swelling, tenderness, and sometimes a bad taste. Deep cleaning addresses it.' },
          { name: 'Gum abscess', desc: 'A small pus pocket along the gumline. Often drains on its own but needs professional treatment to prevent recurrence.' },
          { name: 'Advanced gum disease', desc: 'Persistent gum tenderness that started gradually may indicate periodontitis, which needs deep cleaning and ongoing management.' },
        ],
        note: 'Gum tenderness with swelling that lasts more than a day or two is worth a same-week appointment.',
        guidance: 'urgent',
      },
      'tp-result-persistent': {
        type: 'result', urgency: 'urgent',
        title: 'Ongoing or vague pain — warrants a full exam',
        categories: [
          { name: 'Referred pain from another tooth', desc: 'Pain is surprisingly hard to localize — a lower molar can feel like an upper one. An X-ray and probe test will isolate the source.' },
          { name: 'TMJ / jaw tension', desc: 'Grinding or clenching creates diffuse jaw and tooth pain that mimics a toothache. A night guard evaluation is a good first step.' },
          { name: 'Sinus pressure', desc: 'The roots of upper back teeth sit just below the sinuses. Sinus congestion can create a convincing toothache — with no dental cause.' },
        ],
        note: 'Pain that has lasted more than a week needs a dentist to run a proper differential — X-ray plus sensitivity tests plus a probe exam.',
        guidance: 'urgent',
      },
    },
  },

  'gum-issues': {
    label: 'Gum or mouth issue',
    start: 'gi-1',
    nodes: {
      'gi-1': {
        type: 'q',
        text: "What's happening with your gums or mouth?",
        options: [
          { label: 'Bleeding when I brush or floss',        next: 'gi-2a' },
          { label: 'Swelling or a bump on the gum',         next: 'gi-result-swelling' },
          { label: 'Gums pulling back — teeth look longer', next: 'gi-result-recession' },
          { label: 'A sore or white patch in my mouth',     next: 'gi-result-sore' },
        ],
      },
      'gi-2a': {
        type: 'q',
        text: 'How often does it bleed?',
        options: [
          { label: 'Only when I brush or floss',            next: 'gi-result-gingivitis' },
          { label: 'Spontaneously — without brushing',      next: 'gi-result-periodontitis' },
          { label: 'It bled once after eating something hard', next: 'gi-result-gingivitis' },
        ],
      },

      'gi-result-gingivitis': {
        type: 'result', urgency: 'routine',
        title: 'Bleeding gums — early gingivitis is likely',
        categories: [
          { name: 'Gingivitis', desc: 'Plaque-triggered gum inflammation. Gums bleed easily but are not yet permanently damaged. A professional cleaning and consistent flossing usually resolves it within weeks.' },
          { name: 'Tartar buildup', desc: 'Calculus (hardened plaque) below the gumline irritates gum tissue. Brushing will not remove it — a hygiene visit is needed.' },
          { name: 'Sensitivity to a new product', desc: 'New toothpaste or mouthwash with harsh abrasives can irritate gums temporarily. Switching to a gentle formula often helps.' },
        ],
        note: 'The good news: gingivitis is fully reversible. A cleaning and two weeks of consistent flossing usually stops the bleeding.',
        guidance: 'routine',
      },
      'gi-result-periodontitis': {
        type: 'result', urgency: 'urgent',
        title: 'Spontaneous bleeding — possible periodontitis',
        categories: [
          { name: 'Moderate periodontitis', desc: 'Gum disease that has progressed past gingivitis. Pockets of infection form around the roots. Deep cleaning (scaling and root planing) is the standard treatment.' },
          { name: 'Advanced gum disease', desc: 'Bone loss around teeth, tooth mobility, and significant pocket depths. Requires a periodontist evaluation and often a series of treatments.' },
          { name: 'Hormonal or systemic factor', desc: 'Pregnancy, diabetes, and some medications increase gum bleeding. A dentist will ask about health history to rule these in or out.' },
        ],
        note: 'Gums that bleed without provocation are telling you the infection is more active. A periodontal evaluation is the right first step.',
        guidance: 'urgent',
      },
      'gi-result-swelling': {
        type: 'result', urgency: 'urgent',
        title: 'Gum swelling — see a dentist soon',
        categories: [
          { name: 'Gum or periapical abscess', desc: 'A pocket of infection at the gum or tooth root. Can feel like a pimple on the gum. Without treatment, infection can spread.' },
          { name: 'Dental cyst', desc: 'A fluid-filled sac that develops near a tooth root or a buried tooth. Often painless but visible on an X-ray.' },
          { name: 'Irritation fibroma', desc: 'A benign growth of gum tissue from repeated rubbing — often at the cheek line. Painless, but a dentist should evaluate any persistent bump.' },
        ],
        note: 'A bump on the gum that has been there more than two weeks, or that is tender and growing, should be evaluated promptly.',
        guidance: 'urgent',
      },
      'gi-result-recession': {
        type: 'result', urgency: 'routine',
        title: 'Receding gums — worth evaluating',
        categories: [
          { name: 'Gum recession', desc: 'Root surface becomes exposed as gum tissue pulls back — from brushing too hard, grinding, or gum disease. Exposed roots are sensitive and more cavity-prone.' },
          { name: 'Periodontal bone loss', desc: 'When recession accompanies bone loss, the teeth may eventually loosen. A perio probe measurement confirms severity.' },
          { name: 'Thin gum biotype', desc: 'Some people have naturally thin, fragile gum tissue that recedes more easily — especially around lower front teeth. Gum grafting can protect these areas.' },
        ],
        note: 'Recession does not reverse on its own. A dentist can measure how much has occurred and whether gum grafting is appropriate.',
        guidance: 'routine',
      },
      'gi-result-sore': {
        type: 'result', urgency: 'urgent',
        title: 'Mouth sore or white patch — get it looked at',
        categories: [
          { name: 'Canker sore (aphthous ulcer)', desc: 'Painful white or yellow oval sore inside the cheek or lip. Benign — heals on its own in 1–2 weeks. Recurring sores are worth discussing with a dentist.' },
          { name: 'Oral candidiasis (thrush)', desc: 'White patches that wipe off, leaving a red base. Common in people on antibiotics or steroids, or with a weakened immune system. Treated with antifungal medication.' },
          { name: 'Leukoplakia', desc: 'A white patch that does not wipe off and persists more than 2 weeks. Needs professional evaluation — a biopsy may be recommended to rule out pre-cancerous tissue.' },
        ],
        note: 'Any sore or patch in the mouth that has not healed in 2 weeks should be seen by a dentist or oral surgeon — it is almost certainly benign but always worth confirming.',
        guidance: 'urgent',
      },
    },
  },

  'cosmetic': {
    label: 'Cosmetic concern',
    start: 'cos-1',
    nodes: {
      'cos-1': {
        type: 'q',
        text: 'What is the primary thing you want to improve?',
        options: [
          { label: 'Teeth are stained or discolored',    next: 'cos-result-whitening' },
          { label: 'Chipped, short, or uneven teeth',    next: 'cos-result-bonding' },
          { label: 'Crooked or gapped teeth',            next: 'cos-result-alignment' },
          { label: 'Smile feels too "gummy"',            next: 'cos-result-gummy' },
        ],
      },

      'cos-result-whitening': {
        type: 'result', urgency: 'routine',
        title: 'Discoloration — several options depending on cause',
        categories: [
          { name: 'Extrinsic staining', desc: 'Surface stains from coffee, tea, red wine, and tobacco. Professional cleaning removes most of it; take-home whitening trays handle the rest. Results in 1–2 weeks.' },
          { name: 'Intrinsic discoloration', desc: 'Color that lives inside the tooth — from tetracycline antibiotics, fluorosis, or past trauma. Veneers or bonding are more effective than whitening for intrinsic staining.' },
          { name: 'Old composite or crown shade mismatch', desc: 'Existing restorations do not whiten. If you whiten natural teeth, restorations may appear darker — discuss timing with your dentist.' },
        ],
        note: 'Whitening is safe when done correctly, but not every type of discoloration responds to bleaching. A cosmetic evaluation identifies the right approach.',
        guidance: 'routine',
      },
      'cos-result-bonding': {
        type: 'result', urgency: 'routine',
        title: 'Chips or imperfections — bonding or veneers',
        categories: [
          { name: 'Composite bonding', desc: 'Tooth-colored resin sculpted directly to the tooth. Same-day, reversible, lower cost than veneers. Lasts 5–7 years with good care.' },
          { name: 'Porcelain veneers', desc: 'Thin ceramic shells bonded to the front surface. More durable and stain-resistant than composite. Two visits, higher cost — but the results are very long-lasting.' },
          { name: 'Crown or cap', desc: 'For a tooth that is significantly broken down, a crown covers the whole tooth. More structure removed, but provides the most strength.' },
        ],
        note: 'For a single chipped tooth, bonding is usually the fastest and most conservative option. A cosmetic consultation will show you mockup results before you commit.',
        guidance: 'routine',
      },
      'cos-result-alignment': {
        type: 'result', urgency: 'routine',
        title: 'Crooked or gapped teeth — alignment options',
        categories: [
          { name: 'Clear aligners (Invisalign or similar)', desc: 'Removable clear trays move teeth gradually over months. Near-invisible, comfortable, and easy to clean. Work best for mild to moderate crowding and gaps.' },
          { name: 'Traditional braces', desc: 'Metal or ceramic brackets for more significant movement, including rotation and bite correction. More control for complex cases.' },
          { name: 'Veneers for minor cosmetic gaps', desc: 'If alignment is minor and the main concern is appearance, porcelain veneers can close small gaps without moving teeth at all.' },
        ],
        note: 'An orthodontic consultation determines what is driving the crowding. Treatment time ranges from 6 months (simple gaps) to 2+ years (complex bite issues).',
        guidance: 'routine',
      },
      'cos-result-gummy': {
        type: 'result', urgency: 'routine',
        title: 'Gummy smile — a few causes, a few solutions',
        categories: [
          { name: 'Gum contouring (gingivectomy)', desc: 'A periodontist or cosmetic dentist removes excess gum tissue to expose more of the tooth crown. Quick, often done with a laser, little downtime.' },
          { name: 'Crown lengthening', desc: 'Removes both gum tissue and some bone to expose more tooth structure. Used when the teeth are actually a normal length — just covered by extra gum.' },
          { name: 'Lip repositioning', desc: 'A surgical option that limits how high the lip rises when smiling. Less common, but effective for hyperactive upper lips where gum height is actually normal.' },
        ],
        note: 'Gummy smiles have more than one anatomical cause. A cosmetic evaluation — sometimes with X-rays — identifies whether the gum, bone, or lip is the primary driver.',
        guidance: 'routine',
      },
    },
  },

  'post-op': {
    label: 'After a procedure',
    start: 'po-1',
    nodes: {
      'po-1': {
        type: 'q',
        text: 'What procedure did you have?',
        options: [
          { label: 'Extraction (tooth removed)',          next: 'po-result-extraction' },
          { label: 'Root canal',                         next: 'po-result-rct' },
          { label: 'Filling or crown',                   next: 'po-result-filling' },
          { label: 'Implant or bone graft',              next: 'po-result-implant' },
        ],
      },

      'po-result-extraction': {
        type: 'result', urgency: 'routine',
        title: 'Post-extraction: what is normal vs. not',
        categories: [
          { name: 'Normal healing (1–3 days)', desc: 'Oozing, mild swelling, and a dull ache are expected. Bite on gauze for 30–45 minutes, avoid straws (suction dislodges the clot), eat soft foods, and keep fingers and tongue away from the socket.' },
          { name: 'Dry socket (days 3–5)', desc: 'If the blood clot comes out prematurely, you will feel a sharp, escalating ache radiating toward the ear. The socket will look empty. Call your dentist — they pack it with medicated dressing for fast relief.' },
          { name: 'Signs that need same-day contact', desc: 'Fever over 101°F, spreading facial swelling, heavy bleeding that does not slow after 45 minutes of pressure, or numbness beyond 24 hours — call your dentist or go to urgent care.' },
        ],
        note: 'Most extractions heal uneventfully in 1–2 weeks. Dry socket is the most common complication — treatable in one visit.',
        guidance: 'routine',
      },
      'po-result-rct': {
        type: 'result', urgency: 'routine',
        title: 'Post-root canal: soreness is normal',
        categories: [
          { name: 'Normal post-procedure tenderness', desc: 'The tooth and surrounding gum are sore for 2–5 days after a root canal. OTC ibuprofen (if tolerated) manages it well. The tooth is not infected — the nerve was removed.' },
          { name: 'Flare-up (1–2%)', desc: 'Occasional cases produce significant swelling and pain in the first 48 hours. This is a body response, not treatment failure. Your dentist may add antibiotics or re-open the tooth briefly.' },
          { name: 'Crown timing', desc: 'A root-canal-treated tooth is brittle and needs a crown as soon as practical — usually within 4–6 weeks. Delaying risks cracking the tooth and losing it despite the treatment.' },
        ],
        note: 'Pain that significantly worsens after day 3, or swelling that was not present before, is worth a call to your dentist.',
        guidance: 'routine',
      },
      'po-result-filling': {
        type: 'result', urgency: 'routine',
        title: 'After a filling or crown: common questions',
        categories: [
          { name: 'Bite feels "off"', desc: 'A new filling or crown can feel high for days. If it is still bothering you after 3–4 days, call the office — your dentist can adjust the bite in 5 minutes.' },
          { name: 'Cold or bite sensitivity', desc: 'Post-filling sensitivity to cold or pressure is common for 2–6 weeks, especially for larger fillings close to the nerve. It typically fades on its own.' },
          { name: 'Persistent or worsening pain', desc: 'If pain increases after a week rather than fading, the cavity may have been close enough to the nerve to cause pulpitis. Your dentist will check if a root canal is needed.' },
        ],
        note: 'Filling sensitivity that has not improved after 6 weeks, or that is getting worse, is always worth a follow-up call.',
        guidance: 'routine',
      },
      'po-result-implant': {
        type: 'result', urgency: 'routine',
        title: 'After implant or bone graft: the healing timeline',
        categories: [
          { name: 'First 72 hours', desc: 'Expect swelling (peaks around day 2–3), bruising, and soreness at the surgical site. Keep ice packs on 20 min on / 20 min off for the first 24 hours. Eat soft, cool foods.' },
          { name: 'Osseointegration (weeks to months)', desc: 'The implant fuses with the jaw bone over 3–6 months. Avoid chewing directly on the implant site. Regular follow-ups are essential.' },
          { name: 'Signs to call about promptly', desc: 'Implant mobility, increasing pain after day 5, fever, pus at the site, or an implant that feels loose — these need a same-week evaluation. Implant failure is rare but treatable when caught early.' },
        ],
        note: 'Bone grafts take longer to heal than implants alone — 4–9 months before loading. Your surgeon will tell you exactly when to return.',
        guidance: 'routine',
      },
    },
  },

  'kids': {
    label: "Kid's tooth concern",
    start: 'kids-1',
    nodes: {
      'kids-1': {
        type: 'q',
        text: "What is the concern with your child's tooth or mouth?",
        options: [
          { label: 'Tooth fell out or was knocked loose',        next: 'kids-result-trauma' },
          { label: 'Tooth is visibly decayed or discolored',     next: 'kids-result-decay' },
          { label: 'Is it time for braces or Invisalign?',       next: 'kids-result-ortho' },
          { label: 'Child is anxious about dental visits',       next: 'kids-result-anxiety' },
        ],
      },

      'kids-result-trauma': {
        type: 'result', urgency: 'urgent',
        title: "Knocked-out tooth — act fast",
        categories: [
          { name: 'Baby tooth knocked out', desc: 'Do NOT replant a baby tooth — it can damage the developing adult tooth underneath. Keep the child calm, stop bleeding with gentle gauze pressure, and call your pediatric dentist.' },
          { name: 'Permanent tooth knocked out', desc: 'Time is critical. Pick up by the crown (not the root). If dirty, gently rinse once with milk or water — do not scrub. Store in milk, saline, or between the cheek and gum. Reach a dentist within 30–60 minutes.' },
          { name: 'Tooth pushed in or loose', desc: 'A tooth that has been pushed deeper into the socket or is very mobile needs same-day evaluation. Do not try to reposition it yourself.' },
        ],
        note: 'For a knocked-out permanent tooth, every minute matters. A replanted tooth within 30 minutes has the highest chance of surviving.',
        guidance: 'emergency',
      },
      'kids-result-decay': {
        type: 'result', urgency: 'urgent',
        title: "Cavity in a child's tooth",
        categories: [
          { name: 'Baby tooth cavity', desc: 'Even though baby teeth are temporary, untreated cavities can cause pain, infection, and space loss that affects how permanent teeth come in. Baby teeth often need fillings or crowns.' },
          { name: 'Early permanent tooth cavity', desc: 'Permanent teeth that just erupted have thinner enamel and are more vulnerable. Sealants plus early treatment protect them for decades.' },
          { name: 'Early childhood caries (bottle decay)', desc: 'Patterns of decay across multiple front baby teeth from prolonged bottle or sippy cup use. Often treated under nitrous oxide or sedation. See a pediatric dentist.' },
        ],
        note: 'Kids often do not complain about tooth pain until a cavity is advanced. Routine 6-month checkups catch cavities when they are easy and inexpensive to fix.',
        guidance: 'urgent',
      },
      'kids-result-ortho': {
        type: 'result', urgency: 'routine',
        title: 'Orthodontic evaluation',
        categories: [
          { name: 'When to evaluate', desc: 'The American Association of Orthodontists recommends a first evaluation by age 7. Many issues are monitored then treated after adult teeth come in (age 11–13).' },
          { name: 'Early interceptive treatment', desc: 'Some problems — like crossbites or severe crowding — are treated earlier (ages 7–10) with space maintainers, palate expanders, or partial braces to guide jaw development.' },
          { name: 'Teen aligner vs. braces', desc: 'Most teenagers are candidates for either clear aligners or traditional braces. Compliance (keeping aligners in 22 hours/day) determines which is the better fit.' },
        ],
        note: 'An orthodontic evaluation does not commit to treatment — it just tells you what is happening and when (or whether) to act.',
        guidance: 'routine',
      },
      'kids-result-anxiety': {
        type: 'result', urgency: 'routine',
        title: 'Dental anxiety in children — very common, very manageable',
        categories: [
          { name: 'Pediatric-specialist practice', desc: 'Pediatric dentists train for an extra 2–3 years specifically in child behavior, anxiety management, and communication. Their offices are designed for kids.' },
          { name: 'Tell-show-do and other techniques', desc: 'Good pediatric dentists narrate what they are doing before they do it, use child-friendly names ("Mr. Thirsty" for suction), and never rush. Ask if the practice uses behavior guidance techniques.' },
          { name: 'Nitrous oxide (laughing gas)', desc: 'Inhaled sedation that works in 3–5 minutes, wears off in 3–5 minutes after treatment, and is extremely safe for children. Dramatically reduces anxiety for most kids.' },
        ],
        note: 'A child who has a positive first dental experience is far more likely to be a lifelong dental patient. The right practice matters enormously.',
        guidance: 'routine',
      },
    },
  },
};

/* ── Entry screen ─────────────────────────────────────────────────────────── */
const ENTRY_ORDER = ['tooth-pain', 'gum-issues', 'cosmetic', 'post-op', 'kids'];

const ENTRY_ICONS = {
  'tooth-pain': 'M12 2C7 2 4 6 4 11c0 5 3 9 4 11 .5 1 1 1 1 0 0-2 1-5 3-5s3 3 3 5c0 1 .5 1 1 0 1-2 4-6 4-11 0-5-3-9-8-9z',
  'gum-issues': 'M3 20s1-4 4-6m14 6s-1-4-4-6M12 4v6m0 0c-3 0-5 2-5 5h10c0-3-2-5-5-5z',
  'cosmetic':   'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm0 6c1.5 0 3 .8 4 2M8 9.5C8.8 8.3 10.3 7.5 12 7.5m-4.5 5.5h9',
  'post-op':    'M9 11l3 3L22 4 M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11',
  'kids':       'M12 5c-2 0-4 2-4 5 0 1 .5 2 1 3l-1 4h8l-1-4c.5-1 1-2 1-3 0-3-2-5-4-5zM9 17h6',
};

function EntryCard({ id, lang, onPick }) {
  const tree = TREES[id];
  const label = window.t ? window.t(lang, `dt.entry.${id}`) : tree.label;
  return (
    <button
      type="button"
      onClick={() => onPick(id)}
      className="intent-card"
      style={{
        display: 'flex', flexDirection: 'column', gap: 10,
        textAlign: 'left', alignItems: 'flex-start',
        padding: 'var(--s-5)', background: 'var(--paper)',
        border: '1px solid var(--ink-5)', borderRadius: 'var(--r-5)',
        cursor: 'pointer', color: 'var(--ink-1)',
        transition: 'transform .12s ease, border-color .12s ease, box-shadow .12s ease',
      }}
    >
      <span aria-hidden="true" style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        width: 44, height: 44, borderRadius: 12,
        background: 'var(--bone)', color: 'var(--seal)',
      }}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor"
          strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d={ENTRY_ICONS[id] || ENTRY_ICONS['tooth-pain']}/>
        </svg>
      </span>
      <div style={{ fontWeight: 600, fontSize: 16, lineHeight: 1.3 }}>{label}</div>
      <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>
        {window.t ? window.t(lang, 'btn.continue') : 'Continue'} →
      </div>
    </button>
  );
}

/* ── Question node ────────────────────────────────────────────────────────── */
function QuestionNode({ node, onAnswer, onBack, lang }) {
  return (
    <div className="card" style={{ maxWidth: 640, margin: '0 auto' }}>
      <h2 style={{
        fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 22,
        margin: '0 0 var(--s-2)', lineHeight: 1.3,
      }}>{node.text}</h2>
      {node.sub && (
        <p style={{ margin: '0 0 var(--s-5)', color: 'var(--ink-2)', fontSize: 14 }}>{node.sub}</p>
      )}
      <div style={{ display: 'grid', gap: 'var(--s-2)', marginTop: 'var(--s-4)' }}>
        {node.options.map((opt, i) => (
          <button
            key={i}
            type="button"
            onClick={() => onAnswer(opt.next)}
            style={{
              textAlign: 'left', padding: '12px 16px',
              border: '1px solid var(--ink-5)', borderRadius: 'var(--r-4)',
              background: 'var(--bone)', cursor: 'pointer',
              fontSize: 15, color: 'var(--ink-1)', lineHeight: 1.4,
              transition: 'border-color .1s ease, background .1s ease',
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--ink-3)'; e.currentTarget.style.background = 'var(--paper)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--ink-5)'; e.currentTarget.style.background = 'var(--bone)'; }}
          >
            {opt.label}
          </button>
        ))}
      </div>
      <button
        type="button"
        onClick={onBack}
        style={{
          marginTop: 'var(--s-4)', background: 'transparent', border: 'none',
          cursor: 'pointer', color: 'var(--ink-3)', fontSize: 13, padding: 0,
        }}
      >
        {window.t ? window.t(lang, 'dt.back') : '← Start over'}
      </button>
    </div>
  );
}

/* ── Result node ──────────────────────────────────────────────────────────── */
const URGENCY_CONFIG = {
  emergency: { color: 'var(--alert)',  bg: '#fff0eb', label: 'Possibly urgent — see a dentist today' },
  urgent:    { color: 'var(--seal)',   bg: '#f0f6f4', label: 'See someone this week' },
  routine:   { color: '#5a7a3a',       bg: '#f4f7f0', label: 'Routine — worth booking' },
};

function ResultNode({ node, onRestart, go, lang }) {
  const cfg = URGENCY_CONFIG[node.urgency] || URGENCY_CONFIG.routine;
  const disclaimer = window.t ? window.t(lang, 'dt.disclaimer') : 'This is information, not diagnosis. A licensed dentist must confirm.';

  return (
    <div style={{ maxWidth: 680, margin: '0 auto' }}>
      {/* urgency banner */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, padding: '10px 16px',
        background: cfg.bg, borderRadius: 'var(--r-4)', marginBottom: 'var(--s-5)',
        borderLeft: `3px solid ${cfg.color}`,
      }}>
        <span style={{ fontWeight: 600, fontSize: 14, color: cfg.color }}>
          {cfg.label}
        </span>
      </div>

      <h2 style={{
        fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 26,
        margin: '0 0 var(--s-5)', lineHeight: 1.25,
      }}>{node.title}</h2>

      <div style={{ display: 'grid', gap: 'var(--s-3)', marginBottom: 'var(--s-6)' }}>
        {node.categories.map((cat, i) => (
          <div key={i} className="card card-paper">
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 'var(--s-3)' }}>
              <span style={{
                flexShrink: 0, width: 26, height: 26, borderRadius: '50%',
                background: 'var(--ink-1)', color: 'var(--paper)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'var(--font-display)', fontSize: 13, fontWeight: 500,
              }}>{i + 1}</span>
              <div>
                <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 4 }}>{cat.name}</div>
                <div style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.55 }}>{cat.desc}</div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {node.note && (
        <div style={{
          padding: 'var(--s-4)', background: 'var(--bone)', borderRadius: 'var(--r-4)',
          fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6, marginBottom: 'var(--s-6)',
        }}>
          <strong style={{ color: 'var(--ink-1)' }}>What to watch for: </strong>{node.note}
        </div>
      )}

      <div style={{
        display: 'flex', flexWrap: 'wrap', gap: 'var(--s-3)',
        marginBottom: 'var(--s-4)',
      }}>
        <Button variant="primary" size="md" onClick={() => go('audit-1')}>
          {window.t ? window.t(lang, 'dt.cta.audit') : 'Get a full Smile Snapshot →'}
        </Button>
        <Button variant="secondary" size="md" onClick={() => go('directory')}>
          {window.t ? window.t(lang, 'dt.cta.find') : 'Find a dentist →'}
        </Button>
      </div>

      <button
        type="button"
        onClick={onRestart}
        style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          color: 'var(--ink-3)', fontSize: 13, padding: 0,
        }}
      >
        {window.t ? window.t(lang, 'dt.restart') : 'Different concern'}
      </button>

      <p className="t-fine" style={{ marginTop: 'var(--s-5)' }}>{disclaimer}</p>
    </div>
  );
}

/* ── Main DecisionTree component ──────────────────────────────────────────── */
function DecisionTree({ go, lang, setLang, state, set }) {
  const [treeId, setTreeId] = useState(null);
  const [history, setHistory] = useState([]);   // stack of nodeIds for back nav
  const [nodeId, setNodeId]   = useState(null);

  const pick = (id) => {
    const tree = TREES[id];
    if (!tree) return;
    setTreeId(id);
    setHistory([]);
    setNodeId(tree.start);
  };

  const answer = (nextId) => {
    setHistory(h => [...h, nodeId]);
    setNodeId(nextId);
  };

  const back = () => {
    if (history.length === 0) { reset(); return; }
    const prev = history[history.length - 1];
    setHistory(h => h.slice(0, -1));
    setNodeId(prev);
  };

  const reset = () => {
    setTreeId(null);
    setHistory([]);
    setNodeId(null);
  };

  const title  = window.t ? window.t(lang, 'dt.title') : 'What kind of concern do you have?';
  const sub    = window.t ? window.t(lang, 'dt.sub')   : 'Answer 2–3 quick questions.';

  const currentNode = treeId && nodeId ? TREES[treeId].nodes[nodeId] : null;

  return (
    <div className="app">
      <Masthead lang={lang} setLang={setLang} go={go}/>
      <main>
        <div className="container" style={{ paddingTop: 'var(--s-8)', paddingBottom: 'var(--s-12)' }}>
          <Breadcrumbs
            crumbs={[
              { label: 'Home', screen: 'landing' },
              { label: 'What is this?', screen: 'decision-tree' },
              ...(treeId ? [{ label: TREES[treeId].label }] : []),
            ]}
            go={go}
          />

          {/* Entry screen */}
          {!treeId && (
            <>
              <div style={{ marginBottom: 'var(--s-8)' }}>
                <div className="t-eyebrow" style={{ marginBottom: 'var(--s-2)' }}>Quick dental guide</div>
                <h1 style={{
                  fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 40,
                  margin: '0 0 var(--s-3)', lineHeight: 1.1, maxWidth: '16ch',
                }}>{title}</h1>
                <p style={{ color: 'var(--ink-2)', fontSize: 17, maxWidth: '52ch', margin: 0 }}>{sub}</p>
              </div>
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))',
                gap: 'var(--s-3)',
                marginBottom: 'var(--s-8)',
              }}>
                {ENTRY_ORDER.map(id => (
                  <EntryCard key={id} id={id} lang={lang} onPick={pick}/>
                ))}
              </div>
              <p style={{ fontSize: 13, color: 'var(--ink-3)', textAlign: 'center' }}>
                Want the full triage?{' '}
                <a href="#" onClick={(e) => { e.preventDefault(); go('audit-1'); }}>
                  Take the 90-second Smile Audit →
                </a>
              </p>
            </>
          )}

          {/* Question or result */}
          {treeId && currentNode && currentNode.type === 'q' && (
            <QuestionNode
              node={currentNode}
              onAnswer={answer}
              onBack={back}
              lang={lang}
            />
          )}
          {treeId && currentNode && currentNode.type === 'result' && (
            <ResultNode
              node={currentNode}
              onRestart={reset}
              go={go}
              lang={lang}
            />
          )}
        </div>
      </main>
      <Footer go={go}/>
    </div>
  );
}

window.DecisionTree = DecisionTree;
