// Profile / Progress screen — read-only tracker page user can visit anytime
// Now includes: identity strip with avatar editor, AI Preferences, Voice AI

function ProfileScreen({ pathTitle, milestones, currentIdx, completedActions, avatarFace, avatarImage, userName, onUpdateName, onOpenAvatarPicker, onResume, onClose }) {
  const totalActions = milestones.reduce((s, m) => s + m.actions.length, 0);
  const doneCount = Object.values(completedActions).filter(Boolean).length;
  const pct = Math.round((doneCount / totalActions) * 100);

  const [name, setName] = React.useState(userName || '');
  const [editingName, setEditingName] = React.useState(false);

  // Sync name if prop changes (e.g. API load completes after mount)
  React.useEffect(() => { if (userName) setName(userName); }, [userName]);
  const [activeTab, setActiveTab] = React.useState('progress'); // 'progress' | 'settings'

  // AI Preferences
  const [aiPrefs, setAiPrefs] = React.useState({
    tone: 'encouraging',     // encouraging | direct | analytical
    cadence: 'continuous',   // continuous | weekly | manual
    notify: 'daily',         // daily | weekly | off
    autonomy: 'review',      // ask | review | autonomous
  });
  const updatePref = (k, v) => setAiPrefs((p) => ({ ...p, [k]: v }));

  // Connected accounts
  const [accounts, setAccounts] = React.useState({
    notion: true,
    linkedin: true,
    calendar: false,
    gmail: false,
    slack: false,
  });
  const toggleAccount = (k) => setAccounts((a) => ({ ...a, [k]: !a[k] }));

  // Voice AI
  const [voice, setVoice] = React.useState({
    enabled: false,
    persona: 'aria',         // aria | sage | echo
    activation: 'push',      // push | wake | always
  });
  const updateVoice = (k, v) => setVoice((s) => ({ ...s, [k]: v }));

  return (
    <div className="stage stage-wide profile-stage" data-screen-label="Profile">
      {/* Identity strip */}
      <div className="profile-identity fade-up">
        <div className="profile-identity-avatar-wrap">
          <button
            className="profile-identity-avatar"
            onClick={onOpenAvatarPicker}
            aria-label="Edit avatar"
          >
            {avatarImage
              ? <img src={avatarImage} alt="" className="profile-identity-avatar-img"/>
              : <span className="profile-identity-avatar-face">{avatarFace || '🙂'}</span>}
            <span className="profile-identity-avatar-edit" aria-hidden="true">
              <Icon.Pencil />
            </span>
          </button>
        </div>

        <div className="profile-identity-meta">
          <div className="h-eyebrow" style={{ marginBottom: 8 }}>Your profile</div>
          {editingName ? (
            <input
              autoFocus
              value={name}
              onChange={(e) => setName(e.target.value)}
              onBlur={() => { setEditingName(false); if (onUpdateName) onUpdateName(name); }}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === 'Escape') {
                  setEditingName(false);
                  if (onUpdateName) onUpdateName(name);
                }
              }}
              className="profile-identity-name-input"
            />
          ) : (
            <button
              className="profile-identity-name"
              onClick={() => setEditingName(true)}
              title="Click to edit name"
            >
              {name || 'Your name'}
              <Icon.Pencil style={{ width: 14, height: 14, opacity: 0.5, marginLeft: 10 }} />
            </button>
          )}
          <div className="profile-identity-goal">
            On a path to <span style={{ color: 'var(--v-200)', fontWeight: 500 }}>{pathTitle}</span>
          </div>
          <div className="profile-identity-sub">
            Member since May 2025 · {currentIdx + 1} of {milestones.length} milestones · {pct}% through your path
          </div>
        </div>

        <div className="profile-identity-actions">
          <button className="btn-ghost" onClick={onClose}>
            <Icon.ArrowLeft /> Back
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div className="profile-tabs fade-up delay-1">
        <button
          className={`profile-tab ${activeTab === 'progress' ? 'active' : ''}`}
          onClick={() => setActiveTab('progress')}
        >
          <Icon.Map style={{ width: 14, height: 14 }} /> Progress
        </button>
        <button
          className={`profile-tab ${activeTab === 'settings' ? 'active' : ''}`}
          onClick={() => setActiveTab('settings')}
        >
          <Icon.Sparkle style={{ width: 14, height: 14 }} /> AI &amp; Voice
        </button>
      </div>

      {activeTab === 'progress' && (
        <ProgressTab
          pathTitle={pathTitle}
          milestones={milestones}
          currentIdx={currentIdx}
          completedActions={completedActions}
          avatarFace={avatarFace}
          avatarImage={avatarImage}
          onResume={onResume}
          pct={pct}
          doneCount={doneCount}
          totalActions={totalActions}
        />
      )}

      {activeTab === 'settings' && (
        <SettingsTab
          aiPrefs={aiPrefs}
          updatePref={updatePref}
          accounts={accounts}
          toggleAccount={toggleAccount}
          voice={voice}
          updateVoice={updateVoice}
        />
      )}
    </div>
  );
}

// ============== PROGRESS TAB (original profile content) ==============
function ProgressTab({ pathTitle, milestones, currentIdx, completedActions, avatarFace, avatarImage, onResume, pct, doneCount, totalActions }) {
  return (
    <div className="profile-grid fade-up delay-2">
      <div>
        <div className="profile-stats">
          <div className="profile-stat">
            <div className="profile-stat-label">Plan progress</div>
            <div className="profile-stat-value">{pct}%</div>
            <div className="profile-stat-sub">{doneCount} of {totalActions} actions</div>
          </div>
          <div className="profile-stat">
            <div className="profile-stat-label">Milestone</div>
            <div className="profile-stat-value">{currentIdx + 1} / {milestones.length}</div>
            <div className="profile-stat-sub">{milestones[currentIdx].phase}</div>
          </div>
          <div className="profile-stat">
            <div className="profile-stat-label">Active streak</div>
            <div className="profile-stat-value">4 days</div>
            <div className="profile-stat-sub">Personal best: 11</div>
          </div>
        </div>

        <div className="profile-milestones">
          {milestones.map((m, i) => {
            const done = m.actions.filter((a) => completedActions[a.id]).length;
            const total = m.actions.length;
            const isCurrent = i === currentIdx;
            const isDone = i < currentIdx;
            return (
              <div key={i} className={`profile-milestone ${isCurrent ? 'current' : ''}`}>
                <div className={`profile-milestone-num ${isDone ? 'done' : ''} ${isCurrent ? 'current' : ''}`}>
                  {isDone ? <Icon.Check style={{ width: 13, height: 13 }} /> : (i + 1)}
                </div>
                <div>
                  <div className="profile-milestone-name">{m.title}</div>
                  <div className="profile-milestone-meta">{m.phase} · {total} actions</div>
                </div>
                <div className="profile-milestone-progress">
                  {isDone ? 'Complete' : isCurrent ? `${done}/${total} in progress` : 'Locked'}
                </div>
              </div>
            );
          })}
        </div>

        <div className="profile-activity">
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 14 }}>
            <div style={{ width: 6, height: 6, borderRadius: 3, background: 'var(--co-400)', boxShadow: '0 0 10px var(--co-400)' }}/>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--v-300)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>
              Recent agent activity
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, fontSize: 13.5 }}>
            <ActivityItem time="2m ago" text="Added 3 new FDE openings to your watchlist (Sierra, Decagon, Anthropic)." />
            <ActivityItem time="14m ago" text="Drafted personalized outreach to 5 Anthropic FDEs — waiting for your review." />
            <ActivityItem time="1h ago" text='Re-planned Milestone 2 — Anthropic just posted a new "Applied AI Engineer" role.' />
            <ActivityItem time="yesterday" text="Synced reading list to your Notion. 7 new articles added." />
          </div>
        </div>
      </div>

      <div>
        <div style={{ marginBottom: 14, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--v-300)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>
            The road ahead
          </div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--dim)', letterSpacing: '0.08em' }}>
            Read-only view
          </div>
        </div>
        <Tracker
          milestones={milestones}
          currentIdx={currentIdx}
          avatarFace={avatarFace}
          avatarImage={avatarImage}
          pathTitle={pathTitle}
          onSelectMilestone={() => {}}
        />
        <div style={{ marginTop: 18, textAlign: 'center' }}>
          <button className="btn-primary" onClick={onResume}>
            Resume — Milestone {currentIdx + 1}
            <Icon.ArrowRight />
          </button>
        </div>
      </div>
    </div>
  );
}

// ============== SETTINGS TAB ==============
function SettingsTab({ aiPrefs, updatePref, accounts, toggleAccount, voice, updateVoice }) {
  return (
    <div className="profile-settings fade-up delay-2">
      <AIPreferencesCard aiPrefs={aiPrefs} updatePref={updatePref} accounts={accounts} toggleAccount={toggleAccount} />
      <VoiceAICard voice={voice} updateVoice={updateVoice} />
    </div>
  );
}

// ============== AI PREFERENCES ==============
function AIPreferencesCard({ aiPrefs, updatePref, accounts, toggleAccount }) {
  return (
    <div className="settings-card">
      <div className="settings-card-head">
        <div className="settings-card-icon">
          <Icon.Sparkle />
        </div>
        <div>
          <div className="settings-card-title">AI Preferences</div>
          <div className="settings-card-sub">How your agent thinks, plans, and talks to you.</div>
        </div>
      </div>

      <div className="settings-section">
        <div className="settings-label">Coaching tone</div>
        <div className="settings-help">How the agent frames feedback and progress.</div>
        <Segmented
          value={aiPrefs.tone}
          options={[
            { value: 'encouraging', label: 'Encouraging', desc: 'Warm, motivating' },
            { value: 'direct', label: 'Direct', desc: 'Plain, no fluff' },
            { value: 'analytical', label: 'Analytical', desc: 'Data-driven' },
          ]}
          onChange={(v) => updatePref('tone', v)}
        />
      </div>

      <div className="settings-section">
        <div className="settings-label">Re-planning cadence</div>
        <div className="settings-help">How often the agent rethinks your roadmap based on activity.</div>
        <Segmented
          value={aiPrefs.cadence}
          options={[
            { value: 'continuous', label: 'Continuous', desc: 'Real-time' },
            { value: 'weekly', label: 'Weekly', desc: 'Sunday check-ins' },
            { value: 'manual', label: 'Manual', desc: 'Only on request' },
          ]}
          onChange={(v) => updatePref('cadence', v)}
        />
      </div>

      <div className="settings-section">
        <div className="settings-label">Agent autonomy</div>
        <div className="settings-help">How much the agent does before checking with you.</div>
        <Segmented
          value={aiPrefs.autonomy}
          options={[
            { value: 'ask', label: 'Ask first', desc: 'Confirm every step' },
            { value: 'review', label: 'Draft + review', desc: 'You approve drafts' },
            { value: 'autonomous', label: 'Autonomous', desc: 'Run, then report' },
          ]}
          onChange={(v) => updatePref('autonomy', v)}
        />
      </div>

      <div className="settings-section">
        <div className="settings-label">Notifications</div>
        <div className="settings-help">When the agent gets in touch outside the app.</div>
        <Segmented
          value={aiPrefs.notify}
          options={[
            { value: 'daily', label: 'Daily digest' },
            { value: 'weekly', label: 'Weekly' },
            { value: 'off', label: 'Off' },
          ]}
          onChange={(v) => updatePref('notify', v)}
        />
      </div>

      <div className="settings-divider"/>

      <div className="settings-section">
        <div className="settings-label">Connected accounts</div>
        <div className="settings-help">Sources the agent can read from and write to. You stay in control of every send.</div>
        <div className="settings-accounts">
          <AccountRow id="notion" name="Notion" desc="Reading lists, one-pagers, drafts" icon="N" connected={accounts.notion} onToggle={() => toggleAccount('notion')} />
          <AccountRow id="linkedin" name="LinkedIn" desc="Profile signals, outreach, follows" icon="in" connected={accounts.linkedin} onToggle={() => toggleAccount('linkedin')} />
          <AccountRow id="calendar" name="Google Calendar" desc="Block deep-work time, schedule mocks" icon="C" connected={accounts.calendar} onToggle={() => toggleAccount('calendar')} />
          <AccountRow id="gmail" name="Gmail" desc="Draft applications &amp; cold outreach" icon="M" connected={accounts.gmail} onToggle={() => toggleAccount('gmail')} />
          <AccountRow id="slack" name="Slack" desc="Async check-ins where you already chat" icon="S" connected={accounts.slack} onToggle={() => toggleAccount('slack')} />
        </div>
      </div>
    </div>
  );
}

function AccountRow({ id, name, desc, icon, connected, onToggle }) {
  return (
    <div className={`settings-account ${connected ? 'connected' : ''}`}>
      <div className="settings-account-icon">{icon}</div>
      <div className="settings-account-meta">
        <div className="settings-account-name">{name}</div>
        <div className="settings-account-desc">{desc}</div>
      </div>
      <button
        className={`settings-account-btn ${connected ? 'connected' : ''}`}
        onClick={onToggle}
        aria-label={`${connected ? 'Disconnect' : 'Connect'} ${name}`}
      >
        {connected ? (
          <><Icon.Check style={{ width: 12, height: 12 }} /> Connected</>
        ) : (
          'Connect'
        )}
      </button>
    </div>
  );
}

// ============== VOICE AI ==============
function VoiceAICard({ voice, updateVoice }) {
  const [testing, setTesting] = React.useState(false);

  const personas = [
    { id: 'aria', name: 'Aria', vibe: 'Warm · conversational', sample: '"You shipped 4 actions this week — you\'re moving."' },
    { id: 'sage', name: 'Sage', vibe: 'Calm · thoughtful', sample: '"Let\'s take a step back. What\'s blocking you?"' },
    { id: 'echo', name: 'Echo', vibe: 'Crisp · efficient', sample: '"3 new FDE roles. Best fit: Anthropic. Apply now?"' },
  ];

  return (
    <div className="settings-card">
      <div className="settings-card-head">
        <div className="settings-card-icon voice">
          <Icon.Mic />
        </div>
        <div style={{ flex: 1 }}>
          <div className="settings-card-title">
            Voice AI <span className="settings-badge">NEW</span>
          </div>
          <div className="settings-card-sub">Talk to your agent. Great for walks, commutes, or when you don't feel like typing.</div>
        </div>
        <Toggle checked={voice.enabled} onChange={(v) => updateVoice('enabled', v)} ariaLabel="Enable voice AI" />
      </div>

      <div className={`voice-body ${voice.enabled ? '' : 'disabled'}`}>
        <div className="settings-section">
          <div className="settings-label">Voice persona</div>
          <div className="settings-help">Pick a voice that matches the energy you want. You can swap any time.</div>
          <div className="voice-persona-grid">
            {personas.map((p) => (
              <button
                key={p.id}
                className={`voice-persona ${voice.persona === p.id ? 'active' : ''}`}
                onClick={() => updateVoice('persona', p.id)}
                disabled={!voice.enabled}
              >
                <div className="voice-persona-orb">
                  <span className="voice-persona-orb-inner"/>
                </div>
                <div className="voice-persona-name">{p.name}</div>
                <div className="voice-persona-vibe">{p.vibe}</div>
                <div className="voice-persona-sample">{p.sample}</div>
              </button>
            ))}
          </div>
        </div>

        <div className="settings-section">
          <div className="settings-label">How to start a voice session</div>
          <div className="settings-help">Pick what's least intrusive for how you work.</div>
          <Segmented
            disabled={!voice.enabled}
            value={voice.activation}
            options={[
              { value: 'push', label: 'Push to talk', desc: 'Tap the mic, then speak' },
              { value: 'wake', label: 'Wake word', desc: '"Hey Path…"' },
              { value: 'always', label: 'Always listening', desc: 'Hands-free mode' },
            ]}
            onChange={(v) => updateVoice('activation', v)}
          />
        </div>

        <div className="settings-section voice-test-section">
          <div className="voice-test">
            <button
              className={`voice-test-mic ${testing ? 'testing' : ''}`}
              onClick={() => {
                if (!voice.enabled) return;
                setTesting(true);
                setTimeout(() => setTesting(false), 3000);
              }}
              disabled={!voice.enabled}
              aria-label="Test voice check-in"
            >
              <Icon.Mic />
              {testing && (
                <>
                  <span className="voice-test-ring"/>
                  <span className="voice-test-ring delay-1"/>
                  <span className="voice-test-ring delay-2"/>
                </>
              )}
            </button>
            <div className="voice-test-meta">
              <div className="voice-test-title">
                {testing ? 'Listening…' : 'Try a voice check-in'}
              </div>
              <div className="voice-test-sub">
                {testing
                  ? 'Say anything — the agent is processing.'
                  : 'Tap the mic. Say what you worked on. The agent updates your milestone.'}
              </div>
            </div>
          </div>
        </div>

        <div className="voice-privacy">
          <Icon.Lock style={{ width: 12, height: 12, flexShrink: 0, marginTop: 2 }} />
          <div>
            Voice clips are transcribed and discarded within 24 hours unless you save them.
            Transcripts stay on your account. <a href="#" style={{ color: 'var(--v-200)' }}>Privacy details</a>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============== SHARED CONTROLS ==============
function Segmented({ value, options, onChange, disabled }) {
  return (
    <div className={`segmented ${disabled ? 'disabled' : ''}`} role="radiogroup">
      {options.map((o) => (
        <button
          key={o.value}
          role="radio"
          aria-checked={value === o.value}
          disabled={disabled}
          onClick={() => onChange(o.value)}
          className={`segmented-opt ${value === o.value ? 'active' : ''}`}
        >
          <div className="segmented-opt-label">{o.label}</div>
          {o.desc && <div className="segmented-opt-desc">{o.desc}</div>}
        </button>
      ))}
    </div>
  );
}

function Toggle({ checked, onChange, ariaLabel }) {
  return (
    <button
      role="switch"
      aria-checked={checked}
      aria-label={ariaLabel}
      onClick={() => onChange(!checked)}
      className={`toggle ${checked ? 'on' : ''}`}
    >
      <span className="toggle-knob"/>
    </button>
  );
}

function ActivityItem({ time, text }) {
  return (
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
      <div style={{ width: 4, height: 4, borderRadius: 2, background: 'var(--v-400)', marginTop: 8, flexShrink: 0 }}/>
      <div style={{ flex: 1, color: 'var(--text)', lineHeight: 1.5 }}>{text}</div>
      <div style={{ fontFamily: 'var(--mono)', fontSize: 10, color: 'var(--dim)', flexShrink: 0, marginTop: 3 }}>{time}</div>
    </div>
  );
}

window.ProfileScreen = ProfileScreen;
