// Path Weave — main app shell with full-screen progression

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "avatarFace": "😎",
  "avatarImage": null,
  "showEmergency": true,
  "startScreen": "goal"
}/*EDITMODE-END*/;

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Resume URL state for deep-linking screens during demo
  const initialScreen = (() => {
    const h = window.location.hash.replace('#', '');
    const valid = ['goal', 'discover', 'resume', 'questions', 'refine', 'level', 'celebrate', 'profile'];
    return valid.includes(h) ? h : tweaks.startScreen || 'goal';
  })();

  const [screen, setScreen] = React.useState(initialScreen);
  const [previousScreen, setPreviousScreen] = React.useState('level'); // where to return from profile
  const [goal, setGoal] = React.useState('');
  const [userName, setUserName] = React.useState(null);
  const [resume, setResume] = React.useState('');
  const [selectedPath, setSelectedPath] = React.useState(null);

  // Roadmap state
  const [currentMilestone, setCurrentMilestone] = React.useState(0);
  const [completedActions, setCompletedActions] = React.useState({});
  const [runningActionId, setRunningActionId] = React.useState(null);
  const [verifyModal, setVerifyModal] = React.useState({ open: false, action: null });

  // Emergency
  const [emergencyOpen, setEmergencyOpen] = React.useState(false);
  // Avatar picker
  const [avatarPickerOpen, setAvatarPickerOpen] = React.useState(false);

  // Roadmap API state (populated from backend when available)
  const [roadmapId, setRoadmapId] = React.useState(null);
  const [sessionId, setSessionId] = React.useState(null);

  // Auth state
  const [authReady, setAuthReady] = React.useState(!window._supabase); // true immediately if no Supabase
  const [isAuthed, setIsAuthed] = React.useState(false);

  // Hydrate state from backend on mount — falls back to defaults if unavailable
  React.useEffect(() => {
    if (!window.api || !window.api.isAuthenticated()) return;
    window.api.getActiveState().then((state) => {
      if (!state) return;
      if (state.currentMilestone !== undefined) setCurrentMilestone(state.currentMilestone);
      if (state.completedActions) setCompletedActions(state.completedActions);
      if (state.roadmapId) setRoadmapId(state.roadmapId);
      if (state.userName) setUserName(state.userName);
      if (state.avatarFace) setTweak('avatarFace', state.avatarFace);
    });
  }, []);

  React.useEffect(() => {
    if (!window._supabase) return;
    window._supabase.auth.getSession().then(({ data }) => {
      setIsAuthed(!!data.session);
      setAuthReady(true);
    });
    const { data: { subscription } } = window._supabase.auth.onAuthStateChange((_, session) => {
      setIsAuthed(!!session);
      if (!authReady) setAuthReady(true);
    });
    return () => subscription.unsubscribe();
  }, []);

  React.useEffect(() => {
    if (window.location.hash.replace('#', '') !== screen) {
      history.replaceState(null, '', '#' + screen);
    }
  }, [screen]);

  const goTo = (next, fromCurrentAsPrev = false) => {
    if (fromCurrentAsPrev) setPreviousScreen(screen);
    setScreen(next);
  };

  const goNextOnboarding = () => {
    const flow = ['goal', 'resume', 'questions', 'refine'];
    const i = flow.indexOf(screen);
    if (i >= 0 && i < flow.length - 1) setScreen(flow[i + 1]);
  };
  const goBackOnboarding = () => {
    const flow = ['goal', 'resume', 'questions', 'refine'];
    const i = flow.indexOf(screen);
    if (i > 0) setScreen(flow[i - 1]);
  };

  const handleGoalNext = async () => {
    if (window.api && window.api.isAuthenticated() && !sessionId) {
      const result = await window.api.createSession(goal);
      if (result?.session_id) setSessionId(result.session_id);
    }
    goNextOnboarding();
  };

  const handlePickPath = async (path) => {
    setSelectedPath(path);
    if (window.api && window.api.isAuthenticated() && path.id) {
      const roadmap = await window.api.createRoadmap(path.id);
      if (roadmap?.id) setRoadmapId(roadmap.id);
    }
    setScreen('level');
  };

  const handleToggleAction = (actionId) => {
    const currentlyDone = !!completedActions[actionId];
    if (currentlyDone) {
      // Unmark without verification
      setCompletedActions((prev) => ({ ...prev, [actionId]: false }));
      if (window.api && window.api.isAuthenticated()) {
        window.api.completeAction(actionId, false);
      }
    } else {
      // Require verification before marking complete
      const action = milestoneObj.actions.find((a) => a.id === actionId)
        || { id: actionId, title: 'Complete action', desc: '' };
      setVerifyModal({ open: true, action });
    }
  };

  const handleVerifyConfirm = (actionId) => {
    setCompletedActions((prev) => ({ ...prev, [actionId]: true }));
    if (window.api && window.api.isAuthenticated()) {
      window.api.completeAction(actionId, true);
    }
    setVerifyModal({ open: false, action: null });
  };

  const handleRunAgent = (actionId) => setRunningActionId(actionId);

  const handleLevelComplete = () => {
    setScreen('celebrate');
  };

  const handleContinueToNext = () => {
    const next = currentMilestone + 1;
    if (currentMilestone < FDE_MILESTONES.length - 1) {
      setCurrentMilestone(next);
      if (window.api && window.api.isAuthenticated() && roadmapId) {
        window.api.advanceMilestone(roadmapId, next);
      }
      setScreen('level');
    } else {
      setScreen('profile');
    }
  };

  const handleRestart = () => {
    setScreen('goal');
    setGoal('');
    setSelectedPath(null);
    setCurrentMilestone(0);
    setCompletedActions({});
  };

  const path = selectedPath || { title: 'Forward Deployed Engineer' };
  const milestoneObj = FDE_MILESTONES[currentMilestone];
  const isOnboardingScreen = ['goal', 'discover', 'resume', 'questions', 'refine'].includes(screen);
  const isPathScreen = ['level', 'celebrate', 'profile'].includes(screen);

  // Auth gate — show spinner while checking session, then auth screen if not signed in
  if (!authReady) return <div style={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><span className="dim">Loading…</span></div>;
  if (!isAuthed) return <AuthScreen onAuth={() => setIsAuthed(true)} />;

  return (
    <div data-screen-label={`Path Weave · ${screen}`}>
      {/* Top nav */}
      <nav className="nav">
        <div className="brand" data-screen-label="brand">
          <div className="brand-mark">
            <svg viewBox="0 0 64 64" fill="none">
              <defs>
                <linearGradient id="brandBg" x1="0" y1="0" x2="1" y2="1">
                  <stop offset="0%" stopColor="#a78bfa"/>
                  <stop offset="60%" stopColor="#7c3aed"/>
                  <stop offset="100%" stopColor="#4c1d95"/>
                </linearGradient>
                <linearGradient id="brandStrandA" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#f5f3ff"/>
                  <stop offset="100%" stopColor="#ddd6fe"/>
                </linearGradient>
                <linearGradient id="brandStrandB" x1="1" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#c4b5fd"/>
                  <stop offset="100%" stopColor="#818cf8"/>
                </linearGradient>
              </defs>
              <rect x="2" y="2" width="60" height="60" rx="16" fill="url(#brandBg)"/>
              <rect x="2.5" y="2.5" width="59" height="59" rx="15.5" fill="none" stroke="rgba(255,255,255,0.18)" strokeWidth="1"/>
              {/* Back strand — the "bowl" of the P */}
              <path d="M 22 12 C 22 12, 48 12, 48 26 C 48 40, 22 40, 22 26"
                stroke="url(#brandStrandB)" strokeWidth="6" strokeLinecap="round" fill="none"/>
              {/* Front strand — the stem, woven OVER the bowl */}
              <path d="M 22 12 L 22 52"
                stroke="url(#brandStrandA)" strokeWidth="6.5" strokeLinecap="round" fill="none"/>
              {/* Dashed road markings on the stem */}
              <path d="M 22 16 L 22 48"
                stroke="#4c1d95" strokeWidth="1.2" strokeLinecap="round" strokeDasharray="2 3" opacity="0.55"/>
              {/* Weave-cross node */}
              <circle cx="22" cy="26" r="3.2" fill="url(#brandStrandA)"/>
              <circle cx="22" cy="26" r="1.4" fill="#4c1d95"/>
            </svg>
          </div>
          <div>
            <span className="path-word">Path</span>
            <span className="weave-word">Weave</span>
            <sup>BETA</sup>
          </div>
        </div>
        <div className="nav-right">
          {isPathScreen && screen !== 'profile' && (
            <button
              className="nav-profile-btn"
              onClick={() => setAvatarPickerOpen(true)}
              aria-label="Change your avatar"
            >
              <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--v-200)' }}>
                Milestone {currentMilestone + 1}/{FDE_MILESTONES.length}
              </span>
              <div className="nav-profile-btn-avatar">
                {tweaks.avatarImage
                  ? <img src={tweaks.avatarImage} alt=""/>
                  : tweaks.avatarFace}
              </div>
            </button>
          )}
          {isPathScreen && (
            <button className="chip-btn" onClick={() => alert('Agent would re-rank milestones based on latest activity & opportunities.')}>
              <Icon.Refresh /> Re-plan
            </button>
          )}
          <button className="chip-btn" onClick={handleRestart}>
            <Icon.Refresh /> Restart
          </button>
        </div>
      </nav>

      {/* Screens */}
      <main key={screen}>
        {screen === 'goal' && <GoalEntryScreen goal={goal} setGoal={setGoal} onNext={handleGoalNext} onDiscover={() => setScreen('discover')} />}
        {screen === 'discover' && (
          <DiscoverScreen
            sessionId={sessionId}
            initialStage="questions"
            onPick={(p) => { setSelectedPath(p); setGoal(`I want to become a ${p.title}.`); setScreen('level'); }}
            onBack={() => setScreen('goal')}
          />
        )}
        {screen === 'resume' && <ResumeScreen sessionId={sessionId} goal={goal} resume={resume} setResume={setResume} onNext={goNextOnboarding} onBack={goBackOnboarding} />}
        {screen === 'questions' && <QuestionsScreen sessionId={sessionId} goal={goal} onNext={goNextOnboarding} onBack={goBackOnboarding} />}
        {screen === 'refine' && <RefineScreen sessionId={sessionId} goal={goal} onPick={handlePickPath} onBack={goBackOnboarding} onRedo={() => alert('Agent would re-ask 2 clarifying questions, then rerun the ranking with new weights.')} />}

        {screen === 'level' && (
          <LevelScreen
            milestone={milestoneObj}
            idx={currentMilestone}
            totalMilestones={FDE_MILESTONES.length}
            completedActions={completedActions}
            onToggleAction={handleToggleAction}
            onRunAgent={handleRunAgent}
            runningActionId={runningActionId}
            onComplete={handleLevelComplete}
            onOpenProfile={() => goTo('profile', true)}
            onBack={() => {
              if (currentMilestone === 0) setScreen('refine');
              else { setCurrentMilestone((c) => c - 1); setScreen('celebrate'); }
            }}
          />
        )}

        {screen === 'celebrate' && (
          <CelebrateScreen
            milestone={milestoneObj}
            idx={currentMilestone}
            totalMilestones={FDE_MILESTONES.length}
            isFinal={currentMilestone === FDE_MILESTONES.length - 1}
            onContinue={handleContinueToNext}
            onPause={() => goTo('profile', true)}
            onOpenProfile={() => goTo('profile', true)}
            avatarFace={tweaks.avatarFace}
            avatarImage={tweaks.avatarImage}
            milestones={FDE_MILESTONES}
          />
        )}

        {screen === 'profile' && (
          <ProfileScreen
            pathTitle={path.title}
            milestones={FDE_MILESTONES}
            currentIdx={currentMilestone}
            completedActions={completedActions}
            avatarFace={tweaks.avatarFace}
            avatarImage={tweaks.avatarImage}
            userName={userName}
            onUpdateName={(n) => {
              setUserName(n);
              if (window.api && window.api.isAuthenticated()) window.api.updateProfile({ name: n });
            }}
            onOpenAvatarPicker={() => setAvatarPickerOpen(true)}
            onResume={() => setScreen('level')}
            onClose={() => setScreen(previousScreen === 'profile' ? 'level' : previousScreen)}
          />
        )}
      </main>

      {/* Emergency floating button */}
      {isPathScreen && tweaks.showEmergency && (
        <div className="emergency">
          <button
            className="emergency-btn"
            onClick={() => setEmergencyOpen(true)}
            title="Emergency mode — for when you're between jobs"
          >
            <Icon.SOS />
          </button>
        </div>
      )}
      <EmergencyPanel open={emergencyOpen} onClose={() => setEmergencyOpen(false)} />

      {/* Avatar picker popover */}
      <AvatarPicker
        open={avatarPickerOpen}
        onClose={() => setAvatarPickerOpen(false)}
        currentFace={tweaks.avatarFace}
        currentImage={tweaks.avatarImage}
        onSelectFace={(face) => setTweak({ avatarFace: face, avatarImage: null })}
        onSelectImage={(img) => setTweak({ avatarImage: img })}
      />

      {/* Action verification modal */}
      {verifyModal.open && (
        <VerifyModal
          action={verifyModal.action}
          onConfirm={handleVerifyConfirm}
          onClose={() => setVerifyModal({ open: false, action: null })}
        />
      )}

      {/* Tweaks panel */}
      <TweaksPanel title="Tweaks">
        <TweakSection label="Demo controls">
          <TweakSelect
            label="Jump to screen"
            value={screen}
            options={[
              { value: 'goal', label: '1 · Goal entry' },
              { value: 'discover', label: '1b · Discover (no goal)' },
              { value: 'resume', label: '2 · Resume & profile' },
              { value: 'questions', label: '3 · Agent Q&A' },
              { value: 'refine', label: '4 · Path refinement' },
              { value: 'level', label: '5 · Level (current milestone)' },
              { value: 'celebrate', label: '6 · Celebrate' },
              { value: 'profile', label: '7 · Profile / Progress' },
            ]}
            onChange={(v) => setScreen(v)}
          />
          {isPathScreen && (
            <>
              <TweakSlider
                label={`Current milestone: ${FDE_MILESTONES[currentMilestone].title}`}
                value={currentMilestone}
                min={0}
                max={FDE_MILESTONES.length - 1}
                step={1}
                onChange={(v) => setCurrentMilestone(v)}
              />
              <TweakButton onClick={() => setEmergencyOpen(true)}>
                Open emergency mode
              </TweakButton>
            </>
          )}
        </TweakSection>

        <TweakSection label="Look & feel">
          <TweakSelect
            label="Avatar face"
            value={tweaks.avatarFace}
            options={[
              { value: '😎', label: '😎 Cool' },
              { value: '🤓', label: '🤓 Nerd' },
              { value: '🙂', label: '🙂 Curious' },
              { value: '🤩', label: '🤩 Hyped' },
              { value: '😊', label: '😊 Friendly' },
              { value: '😤', label: '😤 Determined' },
              { value: '👩‍💻', label: '👩‍💻 Coder' },
              { value: '🙋', label: '🙋 Hi there' },
            ]}
            onChange={(v) => setTweak('avatarFace', v)}
          />
          <TweakToggle
            label="Show emergency button"
            value={tweaks.showEmergency}
            onChange={(v) => setTweak('showEmergency', v)}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function Confetti() {
  const pieces = React.useMemo(() => Array.from({ length: 80 }, (_, i) => ({
    left: Math.random() * 100,
    delay: Math.random() * 0.6,
    duration: 1.6 + Math.random() * 1.4,
    color: ['#c084fc', '#818cf8', '#a78bfa', '#d8b4fe', '#c4b5fd'][i % 5],
    rot: Math.random() * 360,
  })), []);
  return (
    <div className="confetti">
      {pieces.map((p, i) => (
        <span key={i} style={{
          left: `${p.left}%`,
          background: p.color,
          animationDelay: `${p.delay}s`,
          animationDuration: `${p.duration}s`,
          transform: `rotate(${p.rot}deg)`,
        }}/>
      ))}
    </div>
  );
}

window.Confetti = Confetti;

const root = ReactDOM.createRoot(document.getElementById('app'));
root.render(<App />);
