/* CHAIRSIDE — the primary workspace. Course content remains in Chairside.html;
   this page only guides the member into learning, AI practice, and review. */
const { useEffect, useMemo } = React;
const COURSE = window.CHAIRSIDE_COURSE;

const ALL_PRODUCTS = (window.SUITE_PRODUCTS || []).flatMap((group) => group.items);
const ADD_ONS = ALL_PRODUCTS.filter((product) => !["course", "my-practice"].includes(product.id));
const FEATURED_ADD_ON_IDS = new Set(["praxia", "eq"]);

function ProgressBar({ value, tokens, accent, label }) {
  return (
    <div
      role="progressbar"
      aria-label={label}
      aria-valuemin="0"
      aria-valuemax="100"
      aria-valuenow={value}
      style={{ height: 6, borderRadius: 3, overflow: "hidden", background: tokens.line }}
    >
      <div style={{ width: `${value}%`, height: "100%", background: accent.c, transition: "width .3s ease" }} />
    </div>
  );
}

function StepLink({ number, title, detail, href, tokens, accent }) {
  return (
    <a className="home-step" href={href}>
      <span className="home-step-number" style={{ color: accent.c, borderColor: accent.c }}>{number}</span>
      <span>
        <strong style={{ display: "block", color: tokens.text, fontSize: 15, marginBottom: 3 }}>{title}</strong>
        <span style={{ color: tokens.soft, fontSize: 13, lineHeight: 1.5 }}>{detail}</span>
      </span>
      <span aria-hidden="true" style={{ color: accent.c, marginLeft: "auto" }}>→</span>
    </a>
  );
}

function AddOnCard({ product, tokens, accessible, entitlementKnown, isOwner, featured = false }) {
  const productAccent = CHAIRSIDE_ACCENTS[product.accent] || CHAIRSIDE_ACCENTS.amber;
  const Wrapper = accessible ? "a" : "div";
  const wrapperProps = accessible
    ? { href: product.href }
    : { "aria-label": `${product.name}, available as an add-on` };
  const status = entitlementKnown
    ? (accessible ? "In your plan" : "Available as add-on")
    : "Add-on";

  return (
    <Wrapper
      {...wrapperProps}
      className={`card add-on-card${accessible ? " lift" : ""}${featured ? " featured" : ""}`}
      style={{
        padding: featured ? 28 : 22,
        display: "flex",
        flexDirection: "column",
        gap: 12,
        minHeight: featured ? 250 : 218,
        borderTop: `3px solid ${productAccent.c}`,
        opacity: accessible ? 1 : 0.78,
      }}
    >
      <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "flex-start" }}>
        <span className="pill" style={{ background: productAccent.soft, color: productAccent.c }}>{status}</span>
        <span className="mono" style={{ color: tokens.mute }}>{product.duration}</span>
      </div>
      <div>
        <h3 className="display" style={{ fontSize: featured ? 27 : 21, marginBottom: 5 }}>{product.name}</h3>
        <div style={{ color: productAccent.c, fontSize: 13, fontWeight: 500 }}>{product.sub}</div>
      </div>
      <p style={{ color: tokens.soft, fontSize: 13, lineHeight: 1.55, margin: 0 }}>
        {product.desc}
      </p>
      <div style={{ marginTop: "auto", paddingTop: 12, borderTop: `1px solid ${tokens.line}`, display: "flex", justifyContent: "space-between", gap: 12 }}>
        <span className="mono" style={{ color: tokens.mute }}>{product.role}</span>
        <span style={{ color: accessible ? productAccent.c : tokens.mute, fontSize: 13, fontWeight: 500 }}>
          {accessible ? "Open →" : isOwner ? "Add to plan" : "Ask practice owner"}
        </span>
      </div>
    </Wrapper>
  );
}

function App() {
  const [tweaks, setTweak] = useTweaks({ theme: "warm", accent: "amber" });
  const tokens = CHAIRSIDE_THEMES[tweaks.theme];
  const accent = CHAIRSIDE_ACCENTS[tweaks.accent];
  const [me, setMe] = useSuiteMe();
  const [progress] = useSyncedStore("chairside.progress", {});

  const entitlements = me && Array.isArray(me.entitlements) ? me.entitlements : null;
  const entitlementKnown = entitlements !== null;
  const isOwner = !!(me && me.isOwner === true);
  const needsRole = !!(me && me.role == null);
  const roleInfo = me && me.role ? suiteRole(me.role) : null;
  const practiceRole = roleInfo ? (suiteRoleToChairside(roleInfo.id) || "tc") : "tc";
  const practiceHref = `Chairside-Roles.html#role=${practiceRole}&view=practice&launch=1`;

  const courseState = useMemo(() => {
    const lessons = COURSE.modules.flatMap((module) => module.lessons.map((lesson) => ({ lesson, module })));
    const done = lessons.filter(({ lesson }) => progress[lesson.id]?.done).length;
    const drillsDone = lessons.filter(({ lesson }) => progress[lesson.id]?.drillDone).length;
    const modulesDone = COURSE.modules.filter((module) => module.lessons.every((lesson) => progress[lesson.id]?.done)).length;
    const next = lessons.find(({ lesson }) => !progress[lesson.id]?.done) || lessons[0];
    const pct = lessons.length ? Math.round((done / lessons.length) * 100) : 0;
    return { lessons, done, drillsDone, modulesDone, next, pct };
  }, [progress]);

  const nextLessonHref = `Chairside.html#view=lesson&module=${courseState.next.module.id}&lesson=${courseState.next.lesson.id}`;
  const featuredAddOns = ADD_ONS.filter((product) => FEATURED_ADD_ON_IDS.has(product.id));
  const supportingAddOns = ADD_ONS.filter((product) => !FEATURED_ADD_ON_IDS.has(product.id));
  const owns = (key) => entitlements === null || entitlements.includes(key);
  const displayName = me && me.displayName ? me.displayName.split(" ")[0] : null;

  useEffect(() => {
    const scrollToSection = () => {
      const id = window.location.hash.replace(/^#/, "");
      if (!id) return;
      const section = document.getElementById(id);
      if (section) section.scrollIntoView({ block: "start" });
    };
    scrollToSection();
    window.addEventListener("hashchange", scrollToSection);
    return () => window.removeEventListener("hashchange", scrollToSection);
  }, []);

  return (
    <>
      <ChairsideStyle tokens={tokens} accent={accent} />
      <style>{`
        .chairside-dashboard h1,
        .chairside-dashboard h2,
        .chairside-dashboard h3,
        .chairside-dashboard h4,
        .chairside-dashboard .display { letter-spacing: 0; }
        .dashboard-title { font-size: 56px; line-height: 1.02; max-width: 720px; }
        .dashboard-grid { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(300px, .85fr); gap: 16px; }
        .dashboard-card { border-radius: 8px; }
        .dashboard-actions { display: flex; gap: 10px; flex-wrap: wrap; }
        .home-step-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
        .home-step { min-height: 112px; display: flex; align-items: center; gap: 14px; padding: 22px 24px; border-right: 1px solid var(--line); }
        .home-step:last-child { border-right: 0; }
        .home-step:hover { background: var(--surface2); }
        .home-step-number { width: 32px; height: 32px; border: 1px solid; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; flex: 0 0 32px; font-family: 'JetBrains Mono', monospace; font-size: 11px; }
        .progress-layout { display: grid; grid-template-columns: minmax(0, 1.2fr) minmax(280px, .8fr); gap: 40px; align-items: center; }
        .progress-stats { display: grid; grid-template-columns: repeat(3, 1fr); border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
        .progress-stat { padding: 20px 18px; border-right: 1px solid var(--line); }
        .progress-stat:last-child { border-right: 0; }
        .featured-add-ons { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
        .supporting-add-ons { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
        .add-on-card { border-radius: 8px; }
        @media (max-width: 1023px) {
          .dashboard-title { font-size: 48px; }
          .supporting-add-ons { grid-template-columns: repeat(2, minmax(0, 1fr)); }
        }
        @media (max-width: 760px) {
          .dashboard-title { font-size: 38px; }
          .dashboard-grid, .progress-layout, .featured-add-ons, .supporting-add-ons { grid-template-columns: 1fr; }
          .home-step-grid { grid-template-columns: 1fr; }
          .home-step { min-height: 92px; border-right: 0; border-bottom: 1px solid var(--line); padding: 18px 4px; }
          .home-step:last-child { border-bottom: 0; }
          .progress-stats { grid-template-columns: 1fr; }
          .progress-stat { border-right: 0; border-bottom: 1px solid var(--line); }
          .progress-stat:last-child { border-bottom: 0; }
          .dashboard-actions .btn { width: 100%; justify-content: center; }
        }
      `}</style>

      <ChairsideHeader product="by Praxia" tokens={tokens} accent={accent} />

      <main className="chairside-dashboard">
        <section style={{ padding: "52px var(--page-pad-x) 40px" }}>
          <div style={{ maxWidth: 1180, margin: "0 auto" }}>
            <div className="eyebrow" style={{ color: accent.c, marginBottom: 12 }}>
              {displayName ? `Welcome back, ${displayName}` : "Chairside by Praxia"}
            </div>
            <h1 className="dashboard-title display" style={{ marginBottom: 16 }}>Chairside communication training.</h1>
            <p style={{ color: tokens.soft, fontSize: 17, lineHeight: 1.6, maxWidth: 670, margin: "0 0 34px" }}>
              Learn the language for patient conversations, practice it with an AI patient, and review what to work on next.
            </p>

            <div className="dashboard-grid">
              <a className="card lift dashboard-card" href={nextLessonHref} style={{ padding: 30, display: "flex", flexDirection: "column", minHeight: 310 }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12, marginBottom: 34 }}>
                  <span className="pill">{courseState.pct > 0 ? "Continue learning" : "Start here"}</span>
                  <span className="mono" style={{ color: tokens.mute }}>{courseState.pct}% complete</span>
                </div>
                <div className="mono" style={{ color: accent.c, marginBottom: 8 }}>
                  Module {courseState.next.module.number} · {courseState.next.module.title}
                </div>
                <h2 className="display" style={{ fontSize: 32, lineHeight: 1.1, marginBottom: 12 }}>{courseState.next.lesson.title}</h2>
                <p style={{ color: tokens.soft, fontSize: 14, lineHeight: 1.55, maxWidth: 620, margin: "0 0 28px" }}>
                  {courseState.next.lesson.brief}
                </p>
                <div style={{ marginTop: "auto" }}>
                  <ProgressBar value={courseState.pct} tokens={tokens} accent={accent} label="Chairside course progress" />
                  <div style={{ display: "flex", justifyContent: "space-between", gap: 16, marginTop: 14, alignItems: "center" }}>
                    <span className="mono" style={{ color: tokens.mute }}>{courseState.done}/{courseState.lessons.length} lessons</span>
                    <span style={{ color: accent.c, fontWeight: 600 }}>Open lesson →</span>
                  </div>
                </div>
              </a>

              <a className="card lift dashboard-card" href={practiceHref} style={{ padding: 30, display: "flex", flexDirection: "column", minHeight: 310, background: tokens.ink, borderColor: tokens.ink, color: tokens.bg }}>
                <div style={{ display: "flex", justifyContent: "space-between", gap: 12, marginBottom: 34, alignItems: "center" }}>
                  <span className="pill" style={{ background: accent.c, color: "white" }}>Practice with AI</span>
                  <span className="mono" style={{ color: `color-mix(in srgb, ${tokens.bg} 62%, transparent)` }}>
                    {roleInfo ? roleInfo.label : "Choose your role"}
                  </span>
                </div>
                <h2 className="display" style={{ color: tokens.bg, fontSize: 32, lineHeight: 1.1, marginBottom: 14 }}>Rehearse the conversation before it happens.</h2>
                <p style={{ color: `color-mix(in srgb, ${tokens.bg} 72%, transparent)`, fontSize: 14, lineHeight: 1.6, margin: 0 }}>
                  Run a live patient scenario by text or voice, receive coaching, and repeat the rep at a harder level.
                </p>
                <div style={{ marginTop: "auto", paddingTop: 28, display: "flex", justifyContent: "space-between", gap: 16, alignItems: "center", borderTop: `1px solid color-mix(in srgb, ${tokens.bg} 20%, transparent)` }}>
                  <span className="mono" style={{ color: `color-mix(in srgb, ${tokens.bg} 62%, transparent)` }}>AI patient practice</span>
                  <span style={{ color: accent.c2, fontWeight: 600 }}>Start a rep →</span>
                </div>
              </a>
            </div>
          </div>
        </section>

        {needsRole && (
          <section style={{ padding: "0 var(--page-pad-x) 42px" }}>
            <div style={{ maxWidth: 1180, margin: "0 auto" }}>
              <SuiteRolePicker
                tokens={tokens}
                accent={accent}
                me={me}
                onSaved={(updated, roleId) => setMe((previous) => updated || (previous ? { ...previous, role: roleId } : previous))}
              />
            </div>
          </section>
        )}

        <section aria-label="Your Chairside path" style={{ padding: "18px var(--page-pad-x) 64px" }}>
          <div style={{ maxWidth: 1180, margin: "0 auto" }}>
            <div className="eyebrow" style={{ color: tokens.mute, marginBottom: 14 }}>Your Chairside rhythm</div>
            <div className="home-step-grid">
              <StepLink number="01" title="Learn" detail="Move through the 12-module Chairside course." href="Chairside.html#view=curriculum" tokens={tokens} accent={accent} />
              <StepLink number="02" title="Practice" detail="Rehearse the same language with an AI patient." href={`Chairside-Roles.html#role=${practiceRole}&view=practice`} tokens={tokens} accent={accent} />
              <StepLink number="03" title="Review" detail="See your scores and choose what to repeat." href="Chairside-My-Practice.html" tokens={tokens} accent={accent} />
            </div>
          </div>
        </section>

        <section id="progress" style={{ padding: "72px var(--page-pad-x)", background: tokens.surface2, scrollMarginTop: 92 }}>
          <div className="progress-layout" style={{ maxWidth: 1180, margin: "0 auto" }}>
            <div>
              <div className="eyebrow" style={{ color: accent.c, marginBottom: 12 }}>Progress</div>
              <h2 className="display" style={{ fontSize: 38, marginBottom: 14 }}>Keep the next step visible.</h2>
              <p style={{ color: tokens.soft, fontSize: 15, lineHeight: 1.65, maxWidth: 610, margin: "0 0 24px" }}>
                Course progress and AI feedback stay connected, so the next lesson and the next practice rep reinforce each other.
              </p>
              <div className="dashboard-actions">
                <a className="btn primary" href="Chairside.html#view=outcomes">Course progress →</a>
                <a className="btn" href="Chairside-My-Practice.html">AI practice history →</a>
              </div>
            </div>
            <div className="progress-stats">
              <div className="progress-stat">
                <div className="display" style={{ fontSize: 32, color: accent.c }}>{courseState.pct}%</div>
                <div style={{ color: tokens.soft, fontSize: 12 }}>Course complete</div>
              </div>
              <div className="progress-stat">
                <div className="display" style={{ fontSize: 32, color: CHAIRSIDE_ACCENTS.teal.c }}>{courseState.modulesDone}/12</div>
                <div style={{ color: tokens.soft, fontSize: 12 }}>Modules complete</div>
              </div>
              <div className="progress-stat">
                <div className="display" style={{ fontSize: 32, color: CHAIRSIDE_ACCENTS.rose.c }}>{courseState.drillsDone}</div>
                <div style={{ color: tokens.soft, fontSize: 12 }}>Drills complete</div>
              </div>
            </div>
          </div>
        </section>

        <section id="add-ons" style={{ padding: "78px var(--page-pad-x) 96px", scrollMarginTop: 92 }}>
          <div style={{ maxWidth: 1180, margin: "0 auto" }}>
            <div style={{ display: "flex", justifyContent: "space-between", gap: 24, alignItems: "end", flexWrap: "wrap", marginBottom: 30 }}>
              <div>
                <div className="eyebrow" style={{ color: CHAIRSIDE_ACCENTS.violet.c, marginBottom: 12 }}>Add-ons</div>
                <h2 className="display" style={{ fontSize: 40, marginBottom: 12 }}>Build more skills when the team is ready.</h2>
                <p style={{ color: tokens.soft, fontSize: 15, lineHeight: 1.6, maxWidth: 680, margin: 0 }}>
                  Chairside remains the starting point. These courses and tools extend the work without interrupting the core path.
                </p>
              </div>
            </div>

            <div className="featured-add-ons" style={{ marginBottom: 16 }}>
              {featuredAddOns.map((product) => (
                <AddOnCard key={product.id} product={product} tokens={tokens} accessible={owns(product.entitlementKey)} entitlementKnown={entitlementKnown} isOwner={isOwner} featured />
              ))}
            </div>
            <div className="supporting-add-ons">
              {supportingAddOns.map((product) => (
                <AddOnCard key={product.id} product={product} tokens={tokens} accessible={owns(product.entitlementKey)} entitlementKnown={entitlementKnown} isOwner={isOwner} />
              ))}
            </div>
          </div>
        </section>

        <footer style={{ borderTop: `1px solid ${tokens.line}`, padding: "28px var(--page-pad-x)" }}>
          <div style={{ maxWidth: 1180, margin: "0 auto", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 18, flexWrap: "wrap" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <ChairsideLogo size={24} accent={accent.c} />
              <span className="display" style={{ fontSize: 17 }}>Chairside by Praxia</span>
            </div>
            <span style={{ color: tokens.mute, fontSize: 13 }}>The art of the yes that helps.</span>
          </div>
        </footer>
      </main>

      <TweaksPanel title="Tweaks">
        <TweakRadio label="Theme" value={tweaks.theme} onChange={(value) => setTweak("theme", value)} options={[{ value: "warm", label: "Warm" }, { value: "cream", label: "Cream" }, { value: "dark", label: "Dark" }]} />
        <TweakSelect label="Accent" value={tweaks.accent} onChange={(value) => setTweak("accent", value)} options={[{ value: "amber", label: "Amber" }, { value: "rose", label: "Rose" }, { value: "teal", label: "Teal" }, { value: "indigo", label: "Indigo" }, { value: "violet", label: "Violet" }]} />
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
