/* global React, I, useState, useEffect, useRef, BrandMark */

// ============================================================================
// KIOSK — patient-facing iPad mode
// What the patient sees: arrival, auth, forms, signature, completion.
// ============================================================================

function Kiosk() {
  const [device, setDevice] = useState("ipad"); // ipad | phone
  const [orientation, setOrientation] = useState("portrait");
  const [step, setStep] = useState("welcome"); // welcome | auth | menu | medhist | consent | review | done | booking

  const KioskStep = { welcome: KioskWelcome, auth: KioskAuth, menu: KioskMenu, medhist: KioskMedHist, consent: KioskConsent, review: KioskReview, done: KioskDone, booking: KioskBooking }[step];

  return (
    <div style={{ flex: 1, display: "flex", overflow: "hidden", background: "linear-gradient(180deg, oklch(96% 0.01 145), oklch(94% 0.012 145))" }}>
      {/* Left rail */}
      <div style={{
        width: 280, borderRight: "1px solid var(--border-hairline)", background: "var(--bg-surface)",
        display: "flex", flexDirection: "column", padding: "16px 16px"
      }}>
        <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 4 }}>Kiosk preview</div>
        <div className="tiny muted" style={{ marginBottom: 18 }}>Live preview of the patient-facing experience.</div>

        <div className="tiny muted medium" style={{ textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Flow</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 2, marginBottom: 24 }}>
          {[
            ["welcome", "Welcome screen", I.Heart],
            ["auth",    "Patient authentication", I.Lock],
            ["menu",    "Forms checklist", I.CheckSquare],
            ["medhist", "Medical history form", I.Stethoscope],
            ["consent", "Procedure consent", I.FileText],
            ["review",  "Review & sign", I.Edit],
            ["done",    "Submitted", I.Check],
            ["booking", "Online booking", I.Calendar],
          ].map(([k, label, IconC]) => (
            <div key={k} onClick={() => setStep(k)} style={{
              display: "flex", alignItems: "center", gap: 10,
              padding: "8px 10px", borderRadius: "var(--r-sm)", cursor: "pointer",
              background: step === k ? "var(--sage-50)" : "transparent",
              color: step === k ? "var(--sage-700)" : "var(--fg-secondary)",
              fontWeight: step === k ? 600 : 450, fontSize: 13
            }}>
              <IconC size={14}/>
              <span>{label}</span>
            </div>
          ))}
        </div>

        <div className="tiny muted medium" style={{ textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>Device</div>
        <div style={{ display: "flex", gap: 6, marginBottom: 12 }}>
          <button onClick={() => setDevice("ipad")} className="btn sm" style={{ flex: 1, background: device === "ipad" ? "var(--bg-subtle)" : "transparent" }}>
            <I.Smartphone size={12}/> iPad
          </button>
          <button onClick={() => setDevice("phone")} className="btn sm" style={{ flex: 1, background: device === "phone" ? "var(--bg-subtle)" : "transparent" }}>
            <I.Smartphone size={12}/> Phone
          </button>
        </div>
        <div style={{ display: "flex", gap: 6, marginBottom: 24 }}>
          <button onClick={() => setOrientation("portrait")} className="btn sm" style={{ flex: 1, background: orientation === "portrait" ? "var(--bg-subtle)" : "transparent" }}>Portrait</button>
          <button onClick={() => setOrientation("landscape")} className="btn sm" style={{ flex: 1, background: orientation === "landscape" ? "var(--bg-subtle)" : "transparent" }}>Landscape</button>
        </div>

        <div className="spacer"/>

        <div className="card" style={{ padding: 12, background: "var(--bg-subtle)", border: "1px dashed var(--border-soft)" }}>
          <div className="tiny medium" style={{ marginBottom: 4 }}>Auto-write back</div>
          <div className="tiny muted" style={{ lineHeight: 1.5 }}>
            Form submissions populate the patient chart immediately and generate alert flags within 1–2 minutes.
          </div>
        </div>
      </div>

      {/* Device stage */}
      <div style={{ flex: 1, display: "grid", placeItems: "center", padding: 32, overflow: "auto" }}>
        <DeviceFrame device={device} orientation={orientation}>
          <KioskStep go={setStep} />
        </DeviceFrame>
      </div>
    </div>
  );
}

function DeviceFrame({ device, orientation, children }) {
  let w, h;
  if (device === "ipad") {
    if (orientation === "portrait") { w = 768; h = 1024; }
    else { w = 1024; h = 768; }
  } else {
    if (orientation === "portrait") { w = 390; h = 844; }
    else { w = 844; h = 390; }
  }
  const scale = Math.min(1, (window.innerHeight - 160) / h, 700 / w);

  return (
    <div style={{
      width: w * scale, height: h * scale,
      position: "relative",
      transition: "width 200ms, height 200ms"
    }}>
      <div style={{
        position: "absolute", inset: 0,
        transform: `scale(${scale})`, transformOrigin: "top left",
        width: w, height: h,
      }}>
        <div style={{
          width: "100%", height: "100%",
          background: "oklch(15% 0.005 240)",
          borderRadius: device === "ipad" ? 38 : 50,
          padding: device === "ipad" ? 14 : 12,
          boxShadow: "0 50px 100px oklch(0% 0 0 / 0.25), 0 20px 40px oklch(0% 0 0 / 0.18)",
        }}>
          <div style={{
            width: "100%", height: "100%",
            background: "var(--bg-canvas)",
            borderRadius: device === "ipad" ? 26 : 40,
            overflow: "hidden",
            position: "relative",
          }}>
            {/* Status bar */}
            <div style={{
              height: 28,
              padding: device === "phone" ? "0 32px 0 28px" : "0 28px",
              display: "flex", alignItems: "center", justifyContent: "space-between",
              fontSize: 13, fontWeight: 600, letterSpacing: "-0.01em",
              color: "var(--fg-primary)"
            }}>
              <span>10:42</span>
              {device === "phone" && (
                <div style={{ width: 96, height: 18, background: "oklch(15% 0.005 240)", borderRadius: 12 }}/>
              )}
              <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                <span style={{ fontSize: 10 }}>●●●</span>
                <span style={{ fontSize: 11 }}>WiFi</span>
                <span style={{
                  width: 22, height: 11, border: "1.5px solid currentColor", borderRadius: 3, position: "relative"
                }}>
                  <span style={{ position: "absolute", inset: 1, background: "currentColor", borderRadius: 1, width: "75%" }}/>
                </span>
              </div>
            </div>
            <div style={{ height: "calc(100% - 28px)", overflow: "hidden", display: "flex", flexDirection: "column" }}>
              {children}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================================
// KIOSK STEPS
// ============================================================================
function KioskWelcome({ go }) {
  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", padding: "60px 48px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <BrandMark size={42}/>
        <div>
          <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.025em" }}>tooth<span style={{color:"var(--sage-500)"}}>·</span>pillow</div>
          <div className="tiny muted">Sunfield Dental · Welcome</div>
        </div>
      </div>

      <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "flex-start", gap: 16 }}>
        <div style={{ fontSize: 38, fontWeight: 600, letterSpacing: "-0.04em", lineHeight: 1.05, color: "var(--fg-primary)" }}>
          Welcome back.<br/>Let's get you ready<br/>for your visit.
        </div>
        <div style={{ fontSize: 16, color: "var(--fg-secondary)", maxWidth: 460, lineHeight: 1.5 }}>
          Tap below to check in. We'll have you authenticate, confirm a few details, and complete any forms before you're seen.
        </div>

        <button onClick={() => go("auth")} style={{
          marginTop: 18,
          padding: "18px 32px",
          background: "var(--sage-600)",
          color: "white",
          border: 0,
          borderRadius: 14,
          fontSize: 17, fontWeight: 600,
          letterSpacing: "-0.01em",
          cursor: "pointer",
          display: "flex", alignItems: "center", gap: 10,
          boxShadow: "0 10px 30px oklch(40% 0.08 145 / 0.3), inset 0 -1px 0 oklch(0% 0 0 / 0.15)"
        }}>
          Check in for my appointment
          <I.ArrowRight size={18}/>
        </button>

        <button onClick={() => go("booking")} style={{
          marginTop: 8,
          padding: "12px 0",
          background: "transparent",
          border: 0,
          color: "var(--fg-secondary)",
          fontSize: 14, fontWeight: 500,
          cursor: "pointer",
          textDecoration: "underline",
          textUnderlineOffset: 4
        }}>
          I don't have an appointment yet — book one now
        </button>
      </div>

      <div style={{ display: "flex", gap: 24, fontSize: 12, color: "var(--fg-tertiary)" }}>
        <span style={{display:"flex", alignItems:"center", gap:6}}><I.Lock size={12}/> HIPAA-compliant</span>
        <span style={{display:"flex", alignItems:"center", gap:6}}><I.Shield size={12}/> Encrypted</span>
        <span style={{display:"flex", alignItems:"center", gap:6}}><I.Globe size={12}/> Español · Français</span>
      </div>
    </div>
  );
}

function KioskAuth({ go }) {
  const [dob, setDob] = useState("");
  const ready = dob.length === 10;
  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", padding: "48px 48px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--fg-tertiary)", fontSize: 13 }}>
        <button onClick={() => go("welcome")} className="btn icon ghost"><I.ChevronLeft size={16}/></button>
        <span>Step 1 of 4</span>
      </div>

      <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center", maxWidth: 480 }}>
        <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: "-0.025em", marginBottom: 10 }}>
          What's your date of birth?
        </div>
        <div style={{ fontSize: 15, color: "var(--fg-secondary)", marginBottom: 28 }}>
          We use this to confirm your identity before you complete your forms.
        </div>

        <div style={{ display: "flex", gap: 10, marginBottom: 24 }}>
          <DobField placeholder="MM" len={2}/>
          <DobField placeholder="DD" len={2}/>
          <DobField placeholder="YYYY" len={4}/>
        </div>

        <button onClick={() => go("menu")} style={{
          padding: "16px 28px",
          background: "var(--sage-600)",
          color: "white",
          border: 0, borderRadius: 12,
          fontSize: 16, fontWeight: 600,
          cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 10,
          alignSelf: "flex-start",
          boxShadow: "0 6px 20px oklch(40% 0.08 145 / 0.25)"
        }}>
          Continue <I.ArrowRight size={16}/>
        </button>
      </div>

      <div className="tiny muted" style={{ display: "flex", alignItems: "center", gap: 6 }}>
        <I.Info size={12}/>
        If your date of birth doesn't match, please ask the front desk for help.
      </div>
    </div>
  );
}

function DobField({ placeholder, len }) {
  const [v, setV] = useState("");
  return (
    <input
      placeholder={placeholder}
      value={v}
      onChange={e => setV(e.target.value.slice(0, len))}
      maxLength={len}
      style={{
        flex: 1,
        height: 80,
        padding: "0 16px",
        fontSize: 32, fontWeight: 600,
        textAlign: "center",
        letterSpacing: "0.04em",
        background: "var(--bg-surface)",
        border: "2px solid var(--border-hairline)",
        borderRadius: 14,
        outline: "none",
        color: "var(--fg-primary)",
        fontVariantNumeric: "tabular-nums"
      }}
    />
  );
}

function KioskMenu({ go }) {
  const FORMS = [
    { id: "medhist", icon: I.Stethoscope, name: "Medical history", est: "5 min", done: false, current: true },
    { id: "consent", icon: I.FileText, name: "Botox consent", est: "2 min", done: false },
    { id: "fin", icon: I.DollarSign, name: "Financial policy", est: "1 min", done: false },
    { id: "ins", icon: I.Shield, name: "Confirm insurance", est: "1 min", done: true },
    { id: "photo", icon: I.User, name: "Take ID photo", est: "30 sec", done: true },
  ];
  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", padding: "32px 40px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <div style={{
          width: 56, height: 56, borderRadius: "50%",
          background: "linear-gradient(135deg, var(--mint-300), var(--sage-500))",
          color: "white", fontSize: 22, fontWeight: 600,
          display: "grid", placeItems: "center"
        }}>MG</div>
        <div>
          <div style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>Hi Monica!</div>
          <div style={{ fontSize: 14, color: "var(--fg-tertiary)" }}>11:00 AM with Dr. Khoury · Operatory 2</div>
        </div>
        <div className="spacer"/>
      </div>

      <div style={{
        marginTop: 24, padding: 16,
        background: "var(--sage-50)", borderRadius: 14,
        border: "1px solid var(--sage-200)",
        display: "flex", alignItems: "center", gap: 12
      }}>
        <I.Clock size={20} style={{ color: "var(--sage-700)" }}/>
        <div>
          <div style={{ fontSize: 14, fontWeight: 600, color: "var(--sage-700)" }}>You have time — take a breath.</div>
          <div style={{ fontSize: 12.5, color: "var(--sage-700)", opacity: 0.85 }}>About 8 minutes of forms remaining. We'll let your hygienist know when you're done.</div>
        </div>
      </div>

      <div style={{ marginTop: 24, marginBottom: 12, fontSize: 14, fontWeight: 600, color: "var(--fg-secondary)" }}>
        Today's checklist
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {FORMS.map(f => (
          <div key={f.id} onClick={() => !f.done && go(f.id === "medhist" ? "medhist" : "consent")} style={{
            display: "flex", alignItems: "center", gap: 16,
            padding: "18px 20px",
            background: f.current ? "var(--bg-surface)" : f.done ? "var(--bg-subtle)" : "var(--bg-surface)",
            border: f.current ? "2px solid var(--sage-500)" : "1px solid var(--border-hairline)",
            borderRadius: 14,
            cursor: f.done ? "default" : "pointer",
            transition: "transform 120ms, border-color 120ms",
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 10,
              background: f.done ? "var(--sage-500)" : f.current ? "var(--sage-50)" : "var(--bg-subtle)",
              color: f.done ? "white" : f.current ? "var(--sage-700)" : "var(--fg-tertiary)",
              display: "grid", placeItems: "center", flexShrink: 0
            }}>
              {f.done ? <I.Check size={20}/> : <f.icon size={20}/>}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 600, textDecoration: f.done ? "line-through" : "none", color: f.done ? "var(--fg-tertiary)" : "var(--fg-primary)" }}>
                {f.name}
              </div>
              <div style={{ fontSize: 12, color: "var(--fg-tertiary)" }}>
                {f.done ? "Completed" : f.current ? "Next · " + f.est : f.est}
              </div>
            </div>
            {!f.done && <I.ChevronRight size={20} style={{ color: "var(--fg-tertiary)" }}/>}
          </div>
        ))}
      </div>

      <div className="spacer"/>

      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 24, fontSize: 12, color: "var(--fg-tertiary)" }}>
        <I.Lock size={12}/>
        Your information is encrypted and only shared with Sunfield Dental.
      </div>
    </div>
  );
}

function KioskMedHist({ go }) {
  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      {/* Top bar */}
      <div style={{ padding: "20px 32px", display: "flex", alignItems: "center", gap: 12, borderBottom: "1px solid var(--border-hairline)", background: "var(--bg-surface)" }}>
        <button onClick={() => go("menu")} className="btn icon ghost"><I.ChevronLeft size={18}/></button>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.015em" }}>Medical history</div>
          <div className="tiny muted">Step 2 of 5 · About 4 minutes</div>
        </div>
        <div style={{ width: 120, height: 6, background: "var(--bg-subtle)", borderRadius: 3 }}>
          <div style={{ width: "40%", height: "100%", background: "var(--sage-500)", borderRadius: 3 }}/>
        </div>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: "28px 32px" }}>
        <div style={{ marginBottom: 28 }}>
          <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 6, letterSpacing: "-0.015em" }}>Do you have any of these conditions?</div>
          <div className="tiny muted">Tap all that apply. Your provider will review with you.</div>
        </div>

        <ConditionGrid />

        <div style={{ marginTop: 32, marginBottom: 12, fontSize: 16, fontWeight: 600, letterSpacing: "-0.015em" }}>
          Are you allergic to any medications or materials?
        </div>
        <KioskChipPicker options={["Penicillin","Latex","Sulfa","Codeine","Peanuts","Iodine","Aspirin","None"]} selected={["Peanuts"]}/>

        <div style={{ marginTop: 32, marginBottom: 12, fontSize: 16, fontWeight: 600, letterSpacing: "-0.015em" }}>
          Are you currently taking any medications?
        </div>
        <textarea placeholder="List your medications, or write 'none'." style={{
          width: "100%", minHeight: 100, padding: 16,
          fontSize: 15, lineHeight: 1.5,
          background: "var(--bg-surface)",
          border: "2px solid var(--border-hairline)",
          borderRadius: 12, outline: "none", resize: "vertical",
          fontFamily: "inherit"
        }}/>

        <div style={{ marginTop: 32 }}>
          <KioskYesNo label="Are you pregnant or nursing?" value="no"/>
          <KioskYesNo label="Are you a smoker?" value="no"/>
          <KioskYesNo label="Do you have any drug or alcohol concerns?" value="no"/>
        </div>
      </div>

      <div style={{ padding: 20, borderTop: "1px solid var(--border-hairline)", background: "var(--bg-surface)", display: "flex", gap: 12 }}>
        <button onClick={() => go("menu")} className="btn lg">Save & finish later</button>
        <div className="spacer"/>
        <button onClick={() => go("review")} style={{
          padding: "14px 28px",
          background: "var(--sage-600)",
          color: "white", border: 0, borderRadius: 12,
          fontSize: 15, fontWeight: 600,
          cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8
        }}>
          Next: Review <I.ArrowRight size={16}/>
        </button>
      </div>
    </div>
  );
}

function ConditionGrid() {
  const ALL = [
    "Anemia","Asthma","Diabetes","High blood pressure","Heart condition","Stroke",
    "Cancer","Thyroid","Liver","Kidney","Arthritis","Bleeding disorder",
    "Anxiety","Depression","Sleep apnea","Migraines","Acid reflux","HIV",
  ];
  const [sel, setSel] = useState(new Set(["Anemia","Asthma","Diabetes"]));
  const toggle = (c) => {
    const n = new Set(sel);
    if (n.has(c)) n.delete(c); else n.add(c);
    setSel(n);
  };
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
      {ALL.map(c => {
        const on = sel.has(c);
        return (
          <div key={c} onClick={() => toggle(c)} style={{
            display: "flex", alignItems: "center", gap: 10,
            padding: "14px 16px",
            background: on ? "var(--sage-50)" : "var(--bg-surface)",
            border: on ? "2px solid var(--sage-500)" : "2px solid var(--border-hairline)",
            borderRadius: 12,
            cursor: "pointer",
            fontSize: 14, fontWeight: 500,
            color: on ? "var(--sage-700)" : "var(--fg-primary)",
            transition: "background 120ms, border-color 120ms",
          }}>
            <div style={{
              width: 20, height: 20, borderRadius: 6,
              border: on ? "2px solid var(--sage-600)" : "2px solid var(--border-strong)",
              background: on ? "var(--sage-600)" : "transparent",
              display: "grid", placeItems: "center", flexShrink: 0
            }}>
              {on && <I.Check size={12} stroke="white" sw={3}/>}
            </div>
            <span>{c}</span>
          </div>
        );
      })}
    </div>
  );
}

function KioskChipPicker({ options, selected = [] }) {
  const [sel, setSel] = useState(new Set(selected));
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
      {options.map(o => {
        const on = sel.has(o);
        return (
          <div key={o} onClick={() => { const n = new Set(sel); n.has(o) ? n.delete(o) : n.add(o); setSel(n); }} style={{
            padding: "10px 18px",
            background: on ? "var(--sage-500)" : "var(--bg-surface)",
            color: on ? "white" : "var(--fg-primary)",
            border: on ? "2px solid var(--sage-600)" : "2px solid var(--border-hairline)",
            borderRadius: 999,
            cursor: "pointer", fontSize: 14, fontWeight: 500
          }}>{o}</div>
        );
      })}
    </div>
  );
}

function KioskYesNo({ label, value }) {
  const [v, setV] = useState(value);
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 16, padding: "14px 0", borderBottom: "1px solid var(--border-hairline)" }}>
      <div style={{ flex: 1, fontSize: 15, fontWeight: 500 }}>{label}</div>
      <div style={{ display: "flex", gap: 6 }}>
        {["yes","no","unsure"].map(opt => (
          <div key={opt} onClick={() => setV(opt)} style={{
            padding: "8px 18px",
            background: v === opt ? "var(--sage-500)" : "var(--bg-surface)",
            color: v === opt ? "white" : "var(--fg-secondary)",
            border: v === opt ? "2px solid var(--sage-600)" : "2px solid var(--border-hairline)",
            borderRadius: 10,
            fontSize: 13, fontWeight: 500,
            cursor: "pointer",
            textTransform: "capitalize"
          }}>{opt}</div>
        ))}
      </div>
    </div>
  );
}

function KioskConsent({ go }) {
  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <div style={{ padding: "20px 32px", display: "flex", alignItems: "center", gap: 12, borderBottom: "1px solid var(--border-hairline)", background: "var(--bg-surface)" }}>
        <button onClick={() => go("menu")} className="btn icon ghost"><I.ChevronLeft size={18}/></button>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.015em" }}>Botox / Filler consent</div>
          <div className="tiny muted">Step 3 of 5</div>
        </div>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: "28px 36px", fontSize: 14, lineHeight: 1.65, color: "var(--fg-primary)" }}>
        <p style={{ fontSize: 15, color: "var(--fg-secondary)" }}>
          Please read this document carefully. By signing below, you acknowledge that you understand the procedure and its risks.
        </p>

        <h3 style={{ fontSize: 16, marginTop: 24, marginBottom: 8 }}>Procedure</h3>
        <p>
          Botulinum toxin (Botox) is injected into specific muscles to temporarily reduce muscle activity. Typical onset is 3–7 days with peak effect at 2 weeks. Effects last 3–4 months on average.
        </p>

        <h3 style={{ fontSize: 16, marginTop: 24, marginBottom: 8 }}>Risks & side effects</h3>
        <ul style={{ paddingLeft: 20 }}>
          <li>Bruising or tenderness at the injection site</li>
          <li>Temporary headache or flu-like symptoms</li>
          <li>Asymmetry or unintended muscle weakness (rare)</li>
          <li>Allergic reaction (very rare)</li>
        </ul>

        <h3 style={{ fontSize: 16, marginTop: 24, marginBottom: 8 }}>Aftercare</h3>
        <p>
          Avoid lying down, rubbing the area, or strenuous exercise for 4 hours after treatment. Results take 7–14 days to fully appear. Please contact us if you have concerns.
        </p>

        <div style={{
          marginTop: 28,
          padding: 16,
          background: "var(--bg-subtle)",
          borderRadius: 12,
          border: "1px solid var(--border-hairline)",
          fontSize: 13
        }}>
          By signing, I confirm that I have read and understand this consent form, my questions have been answered, and I voluntarily consent to the procedure as described.
        </div>

        <div style={{ marginTop: 24 }}>
          <div className="tiny medium" style={{ marginBottom: 8, color: "var(--fg-tertiary)" }}>Sign here</div>
          <SignaturePad />
        </div>
      </div>

      <div style={{ padding: 20, borderTop: "1px solid var(--border-hairline)", background: "var(--bg-surface)", display: "flex", gap: 12 }}>
        <button className="btn lg" onClick={() => go("menu")}>Back</button>
        <div className="spacer"/>
        <button onClick={() => go("review")} style={{
          padding: "14px 28px", background: "var(--sage-600)", color: "white", border: 0, borderRadius: 12,
          fontSize: 15, fontWeight: 600, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8
        }}>
          Sign & continue <I.ArrowRight size={16}/>
        </button>
      </div>
    </div>
  );
}

function SignaturePad() {
  const canvasRef = useRef(null);
  const [drawing, setDrawing] = useState(false);
  const [hasInk, setHasInk] = useState(false);

  useEffect(() => {
    const c = canvasRef.current;
    if (!c) return;
    const dpr = window.devicePixelRatio || 1;
    const rect = c.getBoundingClientRect();
    c.width = rect.width * dpr;
    c.height = rect.height * dpr;
    const ctx = c.getContext("2d");
    ctx.scale(dpr, dpr);
    ctx.strokeStyle = "oklch(22% 0.012 240)";
    ctx.lineWidth = 2.5;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
  }, []);

  const pt = (e) => {
    const c = canvasRef.current;
    const r = c.getBoundingClientRect();
    const x = (e.touches?.[0]?.clientX ?? e.clientX) - r.left;
    const y = (e.touches?.[0]?.clientY ?? e.clientY) - r.top;
    return { x, y };
  };
  const start = (e) => {
    e.preventDefault();
    setDrawing(true);
    setHasInk(true);
    const ctx = canvasRef.current.getContext("2d");
    const { x, y } = pt(e);
    ctx.beginPath();
    ctx.moveTo(x, y);
  };
  const move = (e) => {
    if (!drawing) return;
    e.preventDefault();
    const ctx = canvasRef.current.getContext("2d");
    const { x, y } = pt(e);
    ctx.lineTo(x, y);
    ctx.stroke();
  };
  const end = () => setDrawing(false);
  const clear = () => {
    const c = canvasRef.current;
    c.getContext("2d").clearRect(0, 0, c.width, c.height);
    setHasInk(false);
  };

  return (
    <div>
      <div style={{
        position: "relative",
        background: "var(--bg-surface)",
        border: "2px solid var(--border-hairline)",
        borderRadius: 14,
        height: 160,
        overflow: "hidden"
      }}>
        <canvas
          ref={canvasRef}
          onMouseDown={start} onMouseMove={move} onMouseUp={end} onMouseLeave={end}
          onTouchStart={start} onTouchMove={move} onTouchEnd={end}
          style={{ width: "100%", height: "100%", cursor: "crosshair", touchAction: "none" }}
        />
        {!hasInk && (
          <div style={{
            position: "absolute", inset: 0,
            display: "grid", placeItems: "center",
            color: "var(--fg-quaternary)",
            pointerEvents: "none",
            fontSize: 15, fontStyle: "italic"
          }}>
            ✎ Sign with your finger
          </div>
        )}
        <div style={{
          position: "absolute", bottom: 10, left: 14, right: 14,
          height: 1, background: "var(--border-soft)"
        }}/>
        <div style={{
          position: "absolute", bottom: 14, left: 14,
          fontSize: 11, color: "var(--fg-quaternary)"
        }}>×</div>
      </div>
      <div style={{ display: "flex", marginTop: 8, alignItems: "center", gap: 8 }}>
        <button onClick={clear} className="btn sm ghost">Clear</button>
        <div className="spacer"/>
        <div className="tiny muted">Monica Geller · {new Date().toLocaleDateString()}</div>
      </div>
    </div>
  );
}

function KioskReview({ go }) {
  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <div style={{ padding: "20px 32px", display: "flex", alignItems: "center", gap: 12, borderBottom: "1px solid var(--border-hairline)", background: "var(--bg-surface)" }}>
        <button onClick={() => go("medhist")} className="btn icon ghost"><I.ChevronLeft size={18}/></button>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.015em" }}>Review your answers</div>
          <div className="tiny muted">Tap anywhere to edit</div>
        </div>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: "24px 32px" }}>
        <ReviewCard title="Medical history" status="ready">
          <ReviewRow label="Conditions" value="Anemia · Asthma · Diabetes"/>
          <ReviewRow label="Allergies" value="Peanuts"/>
          <ReviewRow label="Medications" value="None reported"/>
          <ReviewRow label="Pregnant or nursing" value="No"/>
          <ReviewRow label="Smoker" value="No"/>
        </ReviewCard>

        <ReviewCard title="Botox consent" status="signed">
          <ReviewRow label="Procedure" value="Botox injection · masseter / glabella"/>
          <ReviewRow label="Signed" value="Monica Geller · Apr 30, 2026 10:42 AM"/>
        </ReviewCard>

        <ReviewCard title="Financial policy" status="signed">
          <ReviewRow label="Acknowledged" value="Payment terms · cancellation policy"/>
          <ReviewRow label="Signed" value="Monica Geller · Apr 30, 2026 10:39 AM"/>
        </ReviewCard>
      </div>

      <div style={{ padding: 20, borderTop: "1px solid var(--border-hairline)", background: "var(--bg-surface)", display: "flex", gap: 12 }}>
        <button onClick={() => go("medhist")} className="btn lg">Back</button>
        <div className="spacer"/>
        <button onClick={() => go("done")} style={{
          padding: "14px 32px", background: "var(--sage-600)", color: "white", border: 0, borderRadius: 12,
          fontSize: 15, fontWeight: 600, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8
        }}>
          Submit to Sunfield Dental <I.Send size={14}/>
        </button>
      </div>
    </div>
  );
}

function ReviewCard({ title, status, children }) {
  return (
    <div style={{
      marginBottom: 14,
      background: "var(--bg-surface)",
      border: "1px solid var(--border-hairline)",
      borderRadius: 14,
      overflow: "hidden"
    }}>
      <div style={{ padding: "14px 18px", display: "flex", alignItems: "center", gap: 10, borderBottom: "1px solid var(--border-hairline)" }}>
        <div style={{ flex: 1, fontWeight: 600, fontSize: 15 }}>{title}</div>
        {status === "signed" && <span className="chip sage sm"><I.Check size={11}/> Signed</span>}
        {status === "ready" && <span className="chip mint sm"><I.Check size={11}/> Ready</span>}
        <button className="btn icon ghost sm"><I.Edit size={13}/></button>
      </div>
      <div style={{ padding: "8px 18px 16px" }}>{children}</div>
    </div>
  );
}

function ReviewRow({ label, value }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "200px 1fr", gap: 12, padding: "6px 0", alignItems: "flex-start" }}>
      <div className="tiny muted medium">{label}</div>
      <div style={{ fontSize: 13.5 }}>{value}</div>
    </div>
  );
}

function KioskDone({ go }) {
  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", padding: "60px 40px", alignItems: "center", justifyContent: "center", textAlign: "center" }}>
      <div style={{
        width: 96, height: 96, borderRadius: "50%",
        background: "linear-gradient(135deg, var(--mint-300), var(--sage-500))",
        display: "grid", placeItems: "center",
        color: "white",
        boxShadow: "0 20px 50px oklch(40% 0.08 145 / 0.35)",
        animation: "pop-in 400ms cubic-bezier(0.16, 1, 0.3, 1)"
      }}>
        <I.Check size={48} sw={3}/>
      </div>

      <div style={{ marginTop: 28, fontSize: 30, fontWeight: 600, letterSpacing: "-0.025em", lineHeight: 1.1 }}>
        You're all set,<br/>Monica.
      </div>
      <div style={{ marginTop: 12, fontSize: 16, color: "var(--fg-secondary)", maxWidth: 380, lineHeight: 1.5 }}>
        We've sent your information to your provider. Have a seat — they'll come get you in a few minutes.
      </div>

      <div style={{ marginTop: 32, padding: 20, background: "var(--bg-surface)", border: "1px solid var(--border-hairline)", borderRadius: 14, width: "100%", maxWidth: 420 }}>
        <div className="tiny muted medium" style={{ marginBottom: 8, textAlign: "left" }}>Today's appointment</div>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ width: 44, height: 44, borderRadius: 11, background: "var(--violet-50)", color: "var(--violet-700)", display: "grid", placeItems: "center" }}>
            <I.Calendar size={20}/>
          </div>
          <div style={{ textAlign: "left" }}>
            <div style={{ fontWeight: 600, fontSize: 15 }}>11:00 AM · Botox Consult</div>
            <div className="tiny muted">Dr. Khoury · Operatory 2</div>
          </div>
        </div>
      </div>

      <button onClick={() => go("welcome")} className="btn sm ghost" style={{ marginTop: 24 }}>
        Return to start
      </button>
    </div>
  );
}

function KioskBooking({ go }) {
  const [step, setStep] = useState("reason"); // reason | provider | time | confirm
  const [reason, setReason] = useState(null);
  const [provider, setProvider] = useState(null);
  const [slot, setSlot] = useState(null);

  return (
    <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <div style={{ padding: "20px 32px", display: "flex", alignItems: "center", gap: 12, borderBottom: "1px solid var(--border-hairline)", background: "var(--bg-surface)" }}>
        <button onClick={() => go("welcome")} className="btn icon ghost"><I.ChevronLeft size={18}/></button>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: "-0.015em" }}>Book an appointment</div>
          <div className="tiny muted">{step === "reason" ? "What brings you in?" : step === "provider" ? "Choose a provider" : step === "time" ? "Pick a time" : "Confirm"}</div>
        </div>
        <div className="tiny muted">{step === "reason" ? "1" : step === "provider" ? "2" : step === "time" ? "3" : "4"}/4</div>
      </div>

      <div style={{ flex: 1, overflow: "auto", padding: "28px 32px" }}>
        {step === "reason" && <BookReason onPick={(r) => { setReason(r); setStep("provider"); }}/>}
        {step === "provider" && <BookProvider onPick={(p) => { setProvider(p); setStep("time"); }}/>}
        {step === "time" && <BookTime onPick={(s) => { setSlot(s); setStep("confirm"); }}/>}
        {step === "confirm" && <BookConfirm reason={reason} provider={provider} slot={slot} onDone={() => go("done")}/>}
      </div>
    </div>
  );
}

function BookReason({ onPick }) {
  const REASONS = [
    { id: "checkup", label: "Routine checkup & cleaning", icon: I.Tooth, sub: "60 min · every 6 months" },
    { id: "pain", label: "Tooth pain or sensitivity", icon: I.AlertCircle, sub: "30 min · urgent" },
    { id: "cosmetic", label: "Cosmetic consult", icon: I.Sparkles, sub: "30 min · whitening, veneers, botox" },
    { id: "ortho", label: "Ortho consult", icon: I.Activity, sub: "45 min · Invisalign, braces" },
    { id: "emergency", label: "Emergency", icon: I.AlertTriangle, sub: "ASAP · trauma, broken tooth" },
    { id: "other", label: "Something else", icon: I.MoreHorizontal, sub: "Tell us in your own words" },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12 }}>
      {REASONS.map(r => (
        <div key={r.id} onClick={() => onPick(r)} style={{
          padding: "20px 22px",
          background: "var(--bg-surface)",
          border: "2px solid var(--border-hairline)",
          borderRadius: 14, cursor: "pointer",
          display: "flex", flexDirection: "column", gap: 12,
          transition: "border-color 120ms, transform 120ms",
        }}>
          <div style={{ width: 44, height: 44, borderRadius: 11, background: "var(--sage-50)", color: "var(--sage-700)", display: "grid", placeItems: "center" }}>
            <r.icon size={20}/>
          </div>
          <div>
            <div style={{ fontSize: 16, fontWeight: 600 }}>{r.label}</div>
            <div className="tiny muted" style={{ marginTop: 4 }}>{r.sub}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function BookProvider({ onPick }) {
  const PROVS = [
    { id: "any", name: "Any provider", sub: "Soonest available", initials: "—" },
    { id: "tdr", name: "Dr. Tiffany Del Real", sub: "General · Op 4", initials: "TDR" },
    { id: "mr", name: "Dr. Mark Reilly", sub: "Restorative · Op 1", initials: "MR" },
    { id: "sk", name: "Dr. Sara Khoury", sub: "Cosmetic · Op 2", initials: "SK" },
    { id: "rg", name: "Dr. Renu Gupta", sub: "Ortho · Op 6", initials: "RG" },
    { id: "jp", name: "Hyg. Janelle Park", sub: "Hygiene · Op 3", initials: "JP" },
  ];
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      {PROVS.map(p => (
        <div key={p.id} onClick={() => onPick(p)} style={{
          display: "flex", alignItems: "center", gap: 14,
          padding: 16, background: "var(--bg-surface)",
          border: "2px solid var(--border-hairline)",
          borderRadius: 12, cursor: "pointer"
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: "50%",
            background: p.id === "any" ? "var(--bg-subtle)" : "linear-gradient(135deg, var(--mint-300), var(--sage-500))",
            color: "white", display: "grid", placeItems: "center",
            fontSize: 13, fontWeight: 600
          }}>{p.initials}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 15, fontWeight: 600 }}>{p.name}</div>
            <div className="tiny muted">{p.sub}</div>
          </div>
          <I.ChevronRight size={18} style={{ color: "var(--fg-tertiary)" }}/>
        </div>
      ))}
    </div>
  );
}

function BookTime({ onPick }) {
  const [day, setDay] = useState(0);
  const days = ["Tue, May 5", "Wed, May 6", "Thu, May 7", "Fri, May 8", "Mon, May 11"];
  const slots = ["9:00 AM", "9:30 AM", "10:00 AM", "11:30 AM", "1:00 PM", "2:00 PM", "2:30 PM", "3:00 PM", "4:00 PM"];

  return (
    <div>
      <div style={{ display: "flex", gap: 8, marginBottom: 20, overflowX: "auto" }}>
        {days.map((d, i) => (
          <div key={i} onClick={() => setDay(i)} style={{
            padding: "12px 18px",
            background: day === i ? "var(--sage-500)" : "var(--bg-surface)",
            color: day === i ? "white" : "var(--fg-primary)",
            border: day === i ? "2px solid var(--sage-600)" : "2px solid var(--border-hairline)",
            borderRadius: 12, cursor: "pointer",
            fontWeight: 600, fontSize: 14, whiteSpace: "nowrap"
          }}>{d}</div>
        ))}
      </div>

      <div className="tiny muted medium" style={{ marginBottom: 10 }}>MORNING</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8, marginBottom: 20 }}>
        {slots.slice(0, 4).map(s => (
          <div key={s} onClick={() => onPick(s)} style={{
            padding: "16px", background: "var(--bg-surface)",
            border: "2px solid var(--border-hairline)", borderRadius: 12,
            textAlign: "center", fontWeight: 600, fontSize: 15, cursor: "pointer"
          }}>{s}</div>
        ))}
      </div>

      <div className="tiny muted medium" style={{ marginBottom: 10 }}>AFTERNOON</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
        {slots.slice(4).map(s => (
          <div key={s} onClick={() => onPick(s)} style={{
            padding: "16px", background: "var(--bg-surface)",
            border: "2px solid var(--border-hairline)", borderRadius: 12,
            textAlign: "center", fontWeight: 600, fontSize: 15, cursor: "pointer"
          }}>{s}</div>
        ))}
      </div>
    </div>
  );
}

function BookConfirm({ reason, provider, slot, onDone }) {
  return (
    <div style={{ maxWidth: 540, margin: "0 auto" }}>
      <div style={{
        padding: 24, background: "var(--bg-surface)",
        border: "1px solid var(--border-hairline)", borderRadius: 14
      }}>
        <div className="tiny muted medium" style={{ marginBottom: 12 }}>APPOINTMENT SUMMARY</div>
        <ReviewRow label="Reason" value={reason?.label || "—"}/>
        <ReviewRow label="Provider" value={provider?.name || "—"}/>
        <ReviewRow label="When" value={"Thu, May 7 · " + (slot || "—")}/>
        <ReviewRow label="Where" value="Sunfield Dental · 2814 Hillside Dr, Austin TX"/>
        <ReviewRow label="Duration" value={reason?.sub?.split("·")[0]?.trim() || "30 min"}/>
      </div>

      <div style={{ marginTop: 20, display: "flex", gap: 10 }}>
        <button onClick={onDone} style={{
          flex: 1,
          padding: "16px", background: "var(--sage-600)", color: "white",
          border: 0, borderRadius: 12, fontSize: 16, fontWeight: 600, cursor: "pointer"
        }}>
          Confirm appointment
        </button>
      </div>
      <div className="tiny muted" style={{ marginTop: 12, textAlign: "center" }}>
        You'll get a confirmation text. Forms will be sent 5 days before.
      </div>
    </div>
  );
}

Object.assign(window, { Kiosk });
