// ============================================================
// Voice Agent Academy — main shell
// ============================================================
// useState/useEffect/useRef come from React global (declared in lessons.jsx)

const MODULES = [
  { id: 1, title: "Meet your voice agent",     desc: "Voice, brain, hands — the mental model.",                     duration: "3 min", color: "var(--c-voice)",     iconKey: "Mic",        span: "span-4" },
  { id: 2, title: "Create your agent",         desc: "Three picks that set every default that follows.",            duration: "4 min", color: "var(--c-brain)",     iconKey: "Sparkle",    span: "span-4" },
  { id: 3, title: "Configure everything",      desc: "Prompt, voice, brain, languages — without code.",             duration: "6 min", color: "var(--c-config)",    iconKey: "Settings",   span: "span-4" },
  { id: 4, title: "Add your knowledge base",   desc: "Teach it your pricing, SOPs, FAQs — the secret sauce.",       duration: "5 min", color: "var(--c-knowledge)", iconKey: "Book",       span: "span-6" },
  { id: 5, title: "Connect your tools",        desc: "CRMs, scheduling, payments — what makes it actually useful.", duration: "4 min", color: "var(--c-tools)",     iconKey: "Plug",       span: "span-6" },
  { id: 6, title: "Test before you launch",    desc: "Simulate four scenarios. Catch bugs in the browser.",         duration: "4 min", color: "var(--c-test)",      iconKey: "Play",       span: "span-6" },
  { id: 7, title: "Launch — what you can build", desc: "Pick a role. Deploy. Then iterate, weekly.",                duration: "4 min", color: "var(--c-launch)",    iconKey: "Rocket",     span: "span-6" },
];

const INITIAL_STATE = {
  // module 2
  agentType: null,
  industry: null,
  useCase: null,
  // module 3
  systemPrompt: "",
  voice: null,
  llm: null,
  languages: [],
  // module 4
  kbItems: [],
  // module 5
  tools: [],
  // module 6
  testResults: {},
  // module 7
  launchPick: null,
};

const STORAGE_KEY = "vaa_state_v1";

function loadState() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return { build: INITIAL_STATE, completed: [] };
    const parsed = JSON.parse(raw);
    return {
      build: { ...INITIAL_STATE, ...(parsed.build || {}) },
      completed: parsed.completed || [],
    };
  } catch (e) {
    return { build: INITIAL_STATE, completed: [] };
  }
}

function App() {
  const [build, setBuild] = useState(() => loadState().build);
  const [completed, setCompleted] = useState(() => loadState().completed);
  const [openModule, setOpenModule] = useState(null);
  const [toast, setToast] = useState(null);

  // persist
  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify({ build, completed }));
  }, [build, completed]);

  // lock body scroll when overlay open
  useEffect(() => {
    document.body.style.overflow = openModule ? "hidden" : "";
  }, [openModule]);

  const setStatePartial = (patch) => setBuild(b => ({ ...b, ...patch }));

  const isUnlocked = (id) => id === 1 || completed.includes(id - 1);

  const markComplete = (id) => {
    setCompleted(c => c.includes(id) ? c : [...c, id]);
    setToast({ id: Date.now(), msg: `Module ${id} complete!` });
    setTimeout(() => setToast(null), 2400);
  };

  const handleNext = (id) => {
    markComplete(id);
    if (id < MODULES.length) {
      setOpenModule(id + 1);
    } else {
      setOpenModule(null);
    }
  };

  const handleClose = () => setOpenModule(null);

  const progress = (completed.length / MODULES.length) * 100;

  const reset = () => {
    if (!confirm("Reset your progress and start over?")) return;
    setBuild(INITIAL_STATE);
    setCompleted([]);
    setOpenModule(null);
  };

  return (
    <div className="canvas">
      <div className="dot-grid" />

      <header className="topbar">
        <div className="brand">
          <div className="brand-mark">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.2" strokeLinecap="round">
              <path d="M12 3v10" /><path d="M8 7v6" /><path d="M16 7v6" /><path d="M4 11v2" /><path d="M20 11v2" />
            </svg>
          </div>
          <div>
            <div className="brand-name">Voice Agent Academy<span className="brand-sub">v1.0</span></div>
          </div>
        </div>
        <div className="row" style={{ gap: 12 }}>
          <button className="btn btn-ghost" style={{ fontSize: 12, padding: "8px 12px" }} onClick={reset}>Reset</button>
          <div className="progress-pill">
            <div className="progress-bar"><div className="progress-fill" style={{ width: `${progress}%` }} /></div>
            <div><strong>{completed.length}</strong> / {MODULES.length}</div>
          </div>
        </div>
      </header>

      <Hero completedCount={completed.length} total={MODULES.length}
        onStart={() => {
          const nextId = MODULES.find(m => !completed.includes(m.id))?.id || 1;
          setOpenModule(nextId);
        }} />

      <Journey
        modules={MODULES}
        completed={completed}
        openModule={openModule}
        onOpen={(id) => isUnlocked(id) && setOpenModule(id)}
        isUnlocked={isUnlocked} />

      <Footer />

      {openModule && (
        <LessonOverlay
          module={MODULES.find(m => m.id === openModule)}
          state={build}
          setState={setStatePartial}
          onClose={handleClose}
          onNext={() => handleNext(openModule)}
          onPrev={openModule > 1 ? () => setOpenModule(openModule - 1) : null}
          onComplete={() => {
            markComplete(openModule);
            setOpenModule(null);
          }}
          allCompleted={completed.length === MODULES.length}
        />
      )}

      {toast && (
        <div className="toast" key={toast.id}>
          <span className="toast-emoji">
            <window.I.Check />
          </span>
          {toast.msg}
        </div>
      )}
    </div>
  );
}

// ============================================================
function Hero({ completedCount, total, onStart }) {
  const fresh = completedCount === 0;
  const done = completedCount === total;
  return (
    <section className="hero" data-screen-label="Hero">
      <span className="hero-eyebrow"><span className="eyebrow-dot" /> Interactive · 7 modules · 30 min (more if you want to explore)</span>
      <h1>Build a <em>voice AI agent</em>—step by step, no code.</h1>
      <p className="lede">
        A hands-on, click-through walkthrough of every piece of a modern voice agent.
        Each module is a small, simulated workspace — you make the choices, the agent takes shape, and the next module unlocks.
      </p>
      <div className="row" style={{ gap: 12, flexWrap: "wrap" }}>
        <button className="btn btn-primary" style={{ "--accent": "#7c3aed", background: "linear-gradient(120deg, #ff5b9a, #7c3aed)", padding: "14px 22px", fontSize: 15 }} onClick={onStart}>
          {done ? "Review modules" : fresh ? "Start the tutorial" : "Continue where you left off"} <window.I.ArrowRight />
        </button>
        <div className="hero-stats">
          <div className="stat"><div className="stat-num">7</div><div className="stat-lab">modules</div></div>
          <div className="stat"><div className="stat-num">30</div><div className="stat-lab">minutes (or more)</div></div>
        </div>
      </div>
    </section>
  );
}

// ============================================================
// Journey map with SVG connectors
// ============================================================
function Journey({ modules, completed, onOpen, isUnlocked }) {
  return (
    <section className="journey" data-screen-label="Journey map">
      <Connectors modules={modules} />
      <div className="journey-grid">
        {modules.map((m) => (
          <ModuleCard key={m.id}
            module={m}
            unlocked={isUnlocked(m.id)}
            done={completed.includes(m.id)}
            onOpen={() => onOpen(m.id)} />
        ))}
      </div>
    </section>
  );
}

function Connectors({ modules }) {
  // SVG that draws gentle curved dotted lines between consecutive cards
  // We use viewBox auto-fit: position via JS after mount
  const svgRef = useRef(null);
  const [paths, setPaths] = useState([]);

  useEffect(() => {
    const measure = () => {
      const section = svgRef.current?.parentElement;
      if (!section) return;
      const cards = [...section.querySelectorAll(".module-card")];
      const sectionRect = section.getBoundingClientRect();
      const points = cards.map(c => {
        const r = c.getBoundingClientRect();
        return {
          cx: r.left - sectionRect.left + r.width / 2,
          cy: r.top  - sectionRect.top  + r.height / 2,
          top: r.top - sectionRect.top,
          bottom: r.bottom - sectionRect.top,
          left: r.left - sectionRect.left,
          right: r.right - sectionRect.left,
        };
      });
      const newPaths = [];
      for (let i = 0; i < points.length - 1; i++) {
        const a = points[i];
        const b = points[i + 1];
        const sameRow = Math.abs(a.cy - b.cy) < 30;
        let d;
        if (sameRow) {
          // horizontal curve
          const startX = a.right;
          const endX   = b.left;
          const y      = a.cy;
          d = `M ${startX} ${y} C ${startX + 30} ${y}, ${endX - 30} ${y}, ${endX} ${y}`;
        } else {
          // vertical drop to next row
          const startX = a.cx;
          const startY = a.bottom;
          const endX   = b.cx;
          const endY   = b.top;
          const midY   = (startY + endY) / 2;
          d = `M ${startX} ${startY} C ${startX} ${midY}, ${endX} ${midY}, ${endX} ${endY}`;
        }
        newPaths.push({ d, color: modules[i + 1].color });
      }
      setPaths(newPaths);
    };
    measure();
    const ro = new ResizeObserver(measure);
    ro.observe(svgRef.current.parentElement);
    window.addEventListener("resize", measure);
    return () => { ro.disconnect(); window.removeEventListener("resize", measure); };
  }, [modules]);

  return (
    <svg ref={svgRef} className="connectors" preserveAspectRatio="none" width="100%" height="100%">
      {paths.map((p, i) => (
        <path key={i} d={p.d} stroke={p.color} />
      ))}
    </svg>
  );
}

function ModuleCard({ module: m, unlocked, done, onOpen }) {
  const Icon = window.I[m.iconKey];
  return (
    <button
      className={`module-card ${m.span} ${unlocked ? "" : "locked"} ${done ? "done" : ""}`}
      style={{ "--accent": m.color }}
      onClick={onOpen}>
      <div className="module-head">
        <div className="module-num">{String(m.id).padStart(2, "0")}</div>
        <div className="module-icon"><Icon /></div>
      </div>
      <h3 className="module-title">{m.title}</h3>
      <p className="module-desc">{m.desc}</p>
      <div className="module-meta">
        <span>{unlocked ? m.duration : <span className="row" style={{ gap: 4 }}><window.I.Lock /> Locked</span>}</span>
        <span className="arrow"><window.I.ArrowRight /></span>
      </div>
      {done && <div className="check-badge"><window.I.Check /></div>}
    </button>
  );
}

// ============================================================
// Lesson overlay
// ============================================================
function LessonOverlay({ module: m, state, setState, onClose, onNext, onPrev, onComplete, allCompleted }) {
  const lesson = window.LESSONS[m.id];
  if (!lesson) return null;
  const Main = lesson.Main;
  const Side = lesson.Side;
  const isLast = m.id === MODULES.length;
  const Icon = window.I[m.iconKey];

  // close on Esc
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  return (
    <div className="overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
      <div className="lesson" style={{ "--accent": m.color }}>
        <div className="lesson-top">
          <div>
            <div className="lesson-eyebrow">
              <Icon /> Module {String(m.id).padStart(2, "0")} of {String(MODULES.length).padStart(2, "0")}
            </div>
            <h2 className="lesson-title">{m.title}</h2>
          </div>
          <button className="close-btn" onClick={onClose} aria-label="Close lesson">
            <window.I.Close />
          </button>
        </div>

        <div className="lesson-body">
          <div className="lesson-main">
            <Main state={state} setState={setState}
              next={isLast ? onComplete : onNext}
              prev={onPrev}
              complete={onComplete} />
          </div>
          <aside className="lesson-side">
            <Side state={state} />
          </aside>
        </div>

        <div className="lesson-foot">
          <button className="btn" disabled={!onPrev} onClick={onPrev}>
            <window.I.ArrowLeft /> Previous
          </button>
          <div className="lesson-foot-mid">
            <strong>{m.id}</strong> / {MODULES.length} · Press <span className="tag">Esc</span> to close
          </div>
          <button className="btn btn-ghost" style={{ fontSize: 12 }} onClick={onClose}>Save & exit</button>
        </div>
      </div>
    </div>
  );
}

// ============================================================
function Footer() {
  return (
    <footer className="scaffold-foot">
      <div>Voice Agent Academy · An interactive walkthrough</div>
      <div className="row" style={{ gap: 14 }}>
        <span>Progress auto-saved to this browser</span>
      </div>
    </footer>
  );
}

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