/* ROLE PATHS APP — Guided learning tracks UI
 *
 * Role picker → Path overview → Step detail
 * Progress tracked per user, synced to Redis
 */

const { useState, useEffect, useMemo } = React;

function RolePathsRoot() {
  const tokens = window.CHAIRSIDE_THEMES.warm;
  const accent = window.CHAIRSIDE_ACCENTS.teal;
  return (
    <>
      <window.ChairsideStyle tokens={tokens} accent={accent} />
      <window.ChairsideHeader
        product="Role Paths"
        productHref="Chairside-Role-Paths.html"
        tokens={tokens}
        accent={accent}
      />
      <RolePathsApp tokens={tokens} accent={accent} />
    </>
  );
}

function RolePathsApp({ tokens, accent }) {
  const [selectedRoleId, setSelectedRoleId] = window.useChairsideStored("rolePaths.selectedRole", null);
  const [pathProgress, setPathProgress] = window.useSyncedStore("rolePaths.progress", {});
  
  // Deep link support: #role=tc
  useEffect(() => {
    function readHash() {
      const params = new URLSearchParams(window.location.hash.replace(/^#/, ""));
      const roleId = params.get("role");
      if (roleId && window.ROLE_PATHS[roleId]) {
        setSelectedRoleId(roleId);
      }
    }
    readHash();
    window.addEventListener("hashchange", readHash);
    return () => window.removeEventListener("hashchange", readHash);
  }, []);

  const handleSelectRole = (roleId) => {
    setSelectedRoleId(roleId);
    window.location.hash = `role=${roleId}`;
  };

  const handleBack = () => {
    setSelectedRoleId(null);
    window.location.hash = "";
  };

  const markStepComplete = (roleId, stepId) => {
    const roleProgress = pathProgress[roleId] || { completed: [] };
    if (!roleProgress.completed.includes(stepId)) {
      const updated = {
        ...pathProgress,
        [roleId]: {
          ...roleProgress,
          completed: [...roleProgress.completed, stepId],
          lastUpdated: Date.now()
        }
      };
      setPathProgress(updated);
    }
  };

  const markStepIncomplete = (roleId, stepId) => {
    const roleProgress = pathProgress[roleId] || { completed: [] };
    const updated = {
      ...pathProgress,
      [roleId]: {
        ...roleProgress,
        completed: roleProgress.completed.filter(id => id !== stepId),
        lastUpdated: Date.now()
      }
    };
    setPathProgress(updated);
  };

  return (
    <main style={{ background: tokens.bg, minHeight: "100vh" }}>
      {!selectedRoleId ? (
        <RolePathPicker
          tokens={tokens}
          accent={accent}
          onSelectRole={handleSelectRole}
          pathProgress={pathProgress}
        />
      ) : (
        <PathOverview
          tokens={tokens}
          accent={accent}
          roleId={selectedRoleId}
          onBack={handleBack}
          completedSteps={pathProgress[selectedRoleId]?.completed || []}
          onMarkComplete={markStepComplete}
          onMarkIncomplete={markStepIncomplete}
        />
      )}
    </main>
  );
}

// ─── Role Picker ────────────────────────────────────────────────────

function RolePathPicker({ tokens, accent, onSelectRole, pathProgress }) {
  const roles = ["tc", "hyg", "doc", "own"];
  
  return (
    <section style={{ maxWidth: 1320, margin: "0 auto", padding: "80px 28px 120px" }}>
      <div className="pill" style={{ marginBottom: 20 }}>Chairside · Guided Paths</div>
      <h1 className="display" style={{ maxWidth: 980, marginBottom: 20 }}>
        Choose your role path
      </h1>
      <p style={{ fontSize: 19, color: tokens.soft, maxWidth: 720, lineHeight: 1.55, marginBottom: 48 }}>
        Each path combines ordered Learn lessons with matching Practice scenarios. 
        Start where you are, follow the track, and build real skill.
      </p>

      <div style={{ 
        display: "grid", 
        gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", 
        gap: 20,
        marginBottom: 40
      }}>
        {roles.map(roleId => {
          const path = window.ROLE_PATHS[roleId];
          if (!path) return null;
          
          const progress = window.getPathProgress(roleId, pathProgress[roleId]?.completed || []);
          const hasStarted = progress.completed > 0;
          
          return (
            <button
              key={roleId}
              onClick={() => onSelectRole(roleId)}
              style={{
                background: tokens.surface,
                border: `1px solid ${tokens.line}`,
                borderRadius: 16,
                padding: 28,
                textAlign: "left",
                cursor: "pointer",
                transition: "all .2s ease"
              }}
              onMouseOver={(e) => {
                e.currentTarget.style.borderColor = path.color;
                e.currentTarget.style.boxShadow = `0 4px 12px -4px ${path.color}40`;
              }}
              onMouseOut={(e) => {
                e.currentTarget.style.borderColor = tokens.line;
                e.currentTarget.style.boxShadow = "none";
              }}
            >
              <div style={{
                width: 48,
                height: 48,
                borderRadius: 12,
                background: path.color,
                marginBottom: 20,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                color: "white",
                fontSize: 20,
                fontWeight: 600
              }}>
                {path.name.split(" ").map(w => w[0]).join("").slice(0, 2)}
              </div>
              
              <h3 style={{ 
                fontFamily: "Fraunces, serif", 
                fontSize: 22, 
                lineHeight: 1.2, 
                marginBottom: 8,
                color: tokens.text
              }}>
                {path.name}
              </h3>
              
              <p style={{ 
                fontSize: 14, 
                color: tokens.soft, 
                lineHeight: 1.5,
                marginBottom: 20
              }}>
                {path.description}
              </p>

              {hasStarted ? (
                <div>
                  <div style={{
                    height: 6,
                    background: tokens.surface2,
                    borderRadius: 3,
                    overflow: "hidden",
                    marginBottom: 8
                  }}>
                    <div style={{
                      height: "100%",
                      width: `${progress.percent}%`,
                      background: path.color,
                      transition: "width .3s ease"
                    }} />
                  </div>
                  <div style={{ 
                    fontSize: 12, 
                    color: path.color,
                    fontWeight: 500
                  }}>
                    {progress.completed}/{progress.total} complete · {progress.percent}%
                  </div>
                </div>
              ) : (
                <div style={{ 
                  fontSize: 13, 
                  color: tokens.mute,
                  display: "flex",
                  alignItems: "center",
                  gap: 8
                }}>
                  <span>{path.steps.length} steps</span>
                  <span style={{ color: tokens.line }}>·</span>
                  <span>Not started</span>
                </div>
              )}
            </button>
          );
        })}
      </div>

      <div style={{
        background: tokens.surface,
        border: `1px solid ${tokens.line}`,
        borderRadius: 16,
        padding: 28,
        marginTop: 32
      }}>
        <h3 style={{ fontSize: 18, marginBottom: 12 }}>How paths work</h3>
        <ul style={{ 
          listStyle: "none", 
          padding: 0, 
          margin: 0,
          display: "grid",
          gap: 10
        }}>
          <li style={{ 
            display: "flex", 
            gap: 12,
            fontSize: 14,
            lineHeight: 1.5,
            color: tokens.soft
          }}>
            <span style={{ color: accent.c }}>•</span>
            <span><strong style={{ color: tokens.text }}>Learn steps</strong> are lessons from the Chairside course — watch, read, complete the drill</span>
          </li>
          <li style={{ 
            display: "flex", 
            gap: 12,
            fontSize: 14,
            lineHeight: 1.5,
            color: tokens.soft
          }}>
            <span style={{ color: accent.c }}>•</span>
            <span><strong style={{ color: tokens.text }}>Practice steps</strong> are AI roleplay scenarios — run the conversation, get scored</span>
          </li>
          <li style={{ 
            display: "flex", 
            gap: 12,
            fontSize: 14,
            lineHeight: 1.5,
            color: tokens.soft
          }}>
            <span style={{ color: accent.c }}>•</span>
            <span>Progress is saved per role — you can work multiple paths at once</span>
          </li>
          <li style={{ 
            display: "flex", 
            gap: 12,
            fontSize: 14,
            lineHeight: 1.5,
            color: tokens.soft
          }}>
            <span style={{ color: accent.c }}>•</span>
            <span>Your progress syncs across devices when signed in</span>
          </li>
        </ul>
      </div>
    </section>
  );
}

// ─── Path Overview ──────────────────────────────────────────────────

function PathOverview({ tokens, accent, roleId, onBack, completedSteps, onMarkComplete, onMarkIncomplete }) {
  const path = window.ROLE_PATHS[roleId];
  const [expandedStep, setExpandedStep] = useState(null);
  
  if (!path) return null;

  const progress = window.getPathProgress(roleId, completedSteps);
  const nextStep = window.getNextStep(roleId, completedSteps);

  return (
    <section style={{ maxWidth: 960, margin: "0 auto", padding: "80px 28px 120px" }}>
      <button
        onClick={onBack}
        style={{
          background: "transparent",
          border: "none",
          color: accent.c,
          fontSize: 14,
          cursor: "pointer",
          marginBottom: 24,
          display: "flex",
          alignItems: "center",
          gap: 8
        }}
      >
        ← Back to all paths
      </button>

      {/* Path header */}
      <div style={{ marginBottom: 40 }}>
        <div style={{
          display: "flex",
          alignItems: "center",
          gap: 16,
          marginBottom: 16
        }}>
          <div style={{
            width: 64,
            height: 64,
            borderRadius: 16,
            background: path.color,
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            color: "white",
            fontSize: 24,
            fontWeight: 600,
            flexShrink: 0
          }}>
            {path.name.split(" ").map(w => w[0]).join("").slice(0, 2)}
          </div>
          <div style={{ minWidth: 0 }}>
            <div className="eyebrow" style={{ color: path.color, marginBottom: 6 }}>
              Your learning path
            </div>
            <h1 style={{ fontSize: 36, lineHeight: 1.1, margin: 0 }}>{path.name}</h1>
          </div>
        </div>

        <p style={{ 
          fontSize: 17, 
          color: tokens.soft, 
          lineHeight: 1.5,
          marginBottom: 24
        }}>
          {path.description}
        </p>

        {/* Progress bar */}
        <div>
          <div style={{
            height: 8,
            background: tokens.surface2,
            borderRadius: 4,
            overflow: "hidden",
            marginBottom: 12
          }}>
            <div style={{
              height: "100%",
              width: `${progress.percent}%`,
              background: path.color,
              transition: "width .3s ease"
            }} />
          </div>
          <div style={{ 
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            fontSize: 14
          }}>
            <span style={{ color: tokens.text, fontWeight: 500 }}>
              {progress.completed} of {progress.total} steps complete
            </span>
            <span style={{ color: path.color, fontWeight: 600 }}>
              {progress.percent}%
            </span>
          </div>
        </div>

        {/* Next step CTA */}
        {nextStep && (
          <div style={{
            marginTop: 24,
            padding: 20,
            background: `color-mix(in srgb, ${path.color} 8%, ${tokens.surface})`,
            border: `1px solid ${path.color}`,
            borderRadius: 12
          }}>
            <div className="eyebrow" style={{ color: path.color, marginBottom: 8 }}>
              Continue your path
            </div>
            <div style={{ fontSize: 16, fontWeight: 500, marginBottom: 4 }}>
              {nextStep.title}
            </div>
            <div style={{ fontSize: 14, color: tokens.soft, marginBottom: 12 }}>
              {nextStep.description}
            </div>
            <StepActionButton 
              step={nextStep} 
              roleId={roleId}
              color={path.color}
              tokens={tokens}
            />
          </div>
        )}
      </div>

      {/* Steps list */}
      <div style={{ marginTop: 48 }}>
        <h2 style={{ fontSize: 24, marginBottom: 24 }}>All steps</h2>
        <div style={{ display: "grid", gap: 12 }}>
          {path.steps.map((step, index) => {
            const isCompleted = completedSteps.includes(step.id);
            const isExpanded = expandedStep === step.id;
            const isNext = nextStep && nextStep.id === step.id;
            
            return (
              <div
                key={step.id}
                style={{
                  background: tokens.surface,
                  border: `1px solid ${isNext ? path.color : tokens.line}`,
                  borderRadius: 14,
                  overflow: "hidden"
                }}
              >
                <button
                  onClick={() => setExpandedStep(isExpanded ? null : step.id)}
                  style={{
                    width: "100%",
                    textAlign: "left",
                    padding: "18px 20px",
                    background: "transparent",
                    border: "none",
                    cursor: "pointer",
                    display: "grid",
                    gridTemplateColumns: "auto 1fr auto auto",
                    gap: 16,
                    alignItems: "center",
                    color: tokens.text
                  }}
                >
                  {/* Step number */}
                  <div style={{
                    width: 32,
                    height: 32,
                    borderRadius: "50%",
                    background: isCompleted ? path.color : tokens.surface2,
                    color: isCompleted ? "white" : tokens.mute,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    fontSize: 13,
                    fontWeight: 600,
                    flexShrink: 0
                  }}>
                    {isCompleted ? "✓" : index + 1}
                  </div>

                  {/* Step info */}
                  <div style={{ minWidth: 0 }}>
                    <div style={{ 
                      fontSize: 16, 
                      fontWeight: 500,
                      marginBottom: 4,
                      opacity: isCompleted ? 0.7 : 1
                    }}>
                      {step.title}
                    </div>
                    <div style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 10,
                      fontSize: 13,
                      color: tokens.soft,
                      flexWrap: "wrap"
                    }}>
                      <span style={{
                        padding: "2px 8px",
                        borderRadius: 4,
                        background: step.type === "learn" ? "#e6f3ec" : "#f8efd4",
                        color: step.type === "learn" ? "#1f6f4a" : "#8a6a18",
                        fontSize: 11,
                        fontWeight: 600,
                        textTransform: "uppercase",
                        letterSpacing: "0.05em"
                      }}>
                        {step.type}
                      </span>
                      {step.duration && <span>{step.duration} min</span>}
                    </div>
                  </div>

                  {/* Status */}
                  {isNext && !isCompleted && (
                    <span style={{
                      padding: "4px 10px",
                      borderRadius: 999,
                      background: path.color,
                      color: "white",
                      fontSize: 11,
                      fontWeight: 600,
                      textTransform: "uppercase",
                      letterSpacing: "0.05em"
                    }}>
                      Next
                    </span>
                  )}

                  {/* Expand icon */}
                  <span style={{
                    fontSize: 18,
                    color: tokens.mute,
                    transition: "transform .2s",
                    transform: isExpanded ? "rotate(180deg)" : "none"
                  }}>
                    ▼
                  </span>
                </button>

                {/* Expanded content */}
                {isExpanded && (
                  <div style={{
                    padding: "0 20px 24px",
                    borderTop: `1px solid ${tokens.line}`
                  }}>
                    <p style={{
                      fontSize: 14,
                      lineHeight: 1.6,
                      color: tokens.soft,
                      marginTop: 16,
                      marginBottom: 16
                    }}>
                      {step.description}
                    </p>

                    <div style={{ display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center" }}>
                      <StepActionButton 
                        step={step} 
                        roleId={roleId}
                        color={path.color}
                        tokens={tokens}
                      />
                      
                      {!isCompleted ? (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            onMarkComplete(roleId, step.id);
                          }}
                          className="btn"
                          style={{
                            padding: "10px 16px",
                            fontSize: 13,
                            color: tokens.soft,
                            borderColor: tokens.line
                          }}
                        >
                          Mark complete
                        </button>
                      ) : (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            onMarkIncomplete(roleId, step.id);
                          }}
                          className="btn ghost"
                          style={{
                            padding: "10px 16px",
                            fontSize: 13,
                            color: tokens.soft
                          }}
                        >
                          Mark incomplete
                        </button>
                      )}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ─── Step Action Button ─────────────────────────────────────────────

function StepActionButton({ step, roleId, color, tokens }) {
  if (step.type === "learn") {
    // Link to Chairside lesson
    const href = `Chairside.html#view=lesson&module=${step.moduleId}&lesson=${step.lessonId}`;
    return (
      <a
        href={href}
        className="btn primary"
        style={{
          textDecoration: "none",
          padding: "10px 20px",
          fontSize: 13,
          background: color,
          borderColor: color
        }}
      >
        Start lesson →
      </a>
    );
  } else if (step.type === "practice") {
    // Link to Practice with script
    const href = `Chairside-Roles.html#role=${step.roleId}&view=practice&script=${step.scriptId}&launch=1`;
    return (
      <a
        href={href}
        className="btn primary"
        style={{
          textDecoration: "none",
          padding: "10px 20px",
          fontSize: 13,
          background: color,
          borderColor: color
        }}
      >
        Practice with AI →
      </a>
    );
  }
  return null;
}

// Export
Object.assign(window, { RolePathsRoot });
