"""Vastian: Meetings, Councils, and Personas tab views.

HTML templates for the unified app views. Theme and UI prefs from config (vastian data path).
"""

from __future__ import annotations

from pathlib import Path


def render_meetings_view(project_root: Path | None = None) -> str:
    """Meetings + Signals view — meeting list, signal extraction, DIKW tracker."""
    from vastian.ui_theme import get_theme_css

    return _MEETINGS_HTML.replace("__THEME_CSS__", get_theme_css(project_root))


def render_councils_view(user_tier: str, project_root: Path | None = None) -> str:
    """Councils + Mentors view — start council, mentor roster, history."""
    from vastian.ui_theme import get_theme_css

    return _COUNCILS_HTML.replace("__THEME_CSS__", get_theme_css(project_root)).replace(
        "__USER_TIER__", user_tier
    )


def render_personas_view(project_root: Path | None = None) -> str:
    """Personas view with tabs: Radar, Roleplay, Activities, Challenges."""
    from vastian.ui_theme import get_theme_css

    return _PERSONAS_HTML.replace("__THEME_CSS__", get_theme_css(project_root))


_MEETINGS_HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Meetings — Vastian Network</title>
<style>
  __THEME_CSS__
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: var(--text); padding: 24px; }
  h1 { font-size: 1.4em; color: var(--accent); margin-bottom: 8px; }
  .subtitle { color: var(--muted); font-size: 0.9em; margin-bottom: 20px; }
  .card { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 16px; margin-bottom: 16px; }
  .empty { color: var(--muted); padding: 24px; text-align: center; }
  .tab-bar { display: flex; gap: 0; border-bottom: 1px solid var(--border); margin-bottom: 16px; }
  .tab-btn { padding: 10px 20px; background: none; border: none; color: var(--muted); cursor: pointer; font: inherit; font-size: 0.9em; border-bottom: 2px solid transparent; }
  .tab-btn:hover { color: var(--text); }
  .tab-btn.active { color: var(--accent); border-bottom-color: var(--accent); }
  .tab-content { display: none; }
  .tab-content.active { display: block; }
</style>
</head>
<body>
<h1>Meetings + Signals</h1>
<p class="subtitle">Meeting transcripts, extracted signals, and DIKW tracker</p>

<div class="tab-bar">
  <button class="tab-btn active" onclick="switchTab('list')">Meeting List</button>
  <button class="tab-btn" onclick="switchTab('signals')">Signals</button>
  <button class="tab-btn" onclick="switchTab('transcript')">Transcript Viewer</button>
</div>

<div class="tab-content active" id="tab-list">
  <div class="card">
    <div class="empty">
      <p>Upload meeting transcripts for processing.</p>
      <p style="margin-top:12px">Processed meetings will appear here with date, source, and attendees.</p>
    </div>
  </div>
</div>

<div class="tab-content" id="tab-signals">
  <div class="card">
    <div class="empty">Extracted signals (decisions, action items, blockers, risks, ideas) organized by meeting. Coming soon.</div>
  </div>
</div>

<div class="tab-content" id="tab-transcript">
  <div class="card">
    <div class="empty">Select a meeting to view the full transcript with signal highlights.</div>
  </div>
</div>

<script>
function switchTab(tab) {
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
  document.querySelector('[onclick="switchTab(\'' + tab + '\')"]').classList.add('active');
  document.getElementById('tab-' + tab).classList.add('active');
}
</script>
</body>
</html>
"""

_COUNCILS_HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Councils — Vastian Network</title>
<style>
  __THEME_CSS__
  :root { --green:#3fb950; }
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body { font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: var(--text); padding: 24px; }
  h1 { font-size: 1.4em; color: var(--accent); margin-bottom: 8px; }
  .subtitle { color: var(--muted); font-size: 0.9em; margin-bottom: 20px; }
  .card { background: var(--card); border: 1px solid var(--border); border-radius: 8px; padding: 16px; margin-bottom: 16px; }
  .card h2 { font-size: 1.1em; color: var(--accent); margin-bottom: 12px; }
  .form-row { margin-bottom: 12px; }
  .form-row label { display: block; color: var(--muted); font-size: 0.85em; margin-bottom: 4px; }
  .form-row input, .form-row select { width: 100%; max-width: 400px; background: var(--bg); border: 1px solid var(--border); color: var(--text); padding: 8px 12px; border-radius: 6px; font: inherit; }
  button { background: var(--accent); color: #fff; border: none; padding: 8px 20px; border-radius: 6px; cursor: pointer; font: inherit; font-size: 0.9em; }
  button:hover { opacity: 0.9; }
  button:disabled { opacity: 0.5; cursor: not-allowed; }
  .session-list { display: flex; flex-direction: column; gap: 8px; }
  .session-item { padding: 12px; background: var(--bg); border-radius: 6px; border: 1px solid var(--border); cursor: pointer; }
  .session-item:hover { border-color: var(--accent); }
  .mentor-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 10px; }
  .mentor-card { padding: 12px; background: var(--bg); border-radius: 6px; border: 1px solid var(--border); font-size: 0.9em; }
  .empty { color: var(--muted); padding: 24px; text-align: center; }
  .toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background: var(--green); color: #fff; padding: 8px 20px; border-radius: 8px; opacity: 0; transition: opacity 0.3s; }
  .toast.show { opacity: 1; }
</style>
</head>
<body>
<h1>Councils + Mentors</h1>
<p class="subtitle">Mentor council meetings and individual mentor chat — Tier: __USER_TIER__</p>

<div class="card">
  <h2>Start Council</h2>
  <div class="form-row">
    <label>Topic</label>
    <input type="text" id="councilTopic" placeholder="e.g. Career pivot decision">
  </div>
  <div class="form-row">
    <label>Council Type</label>
    <select id="councilType">
      <option value="ad_hoc">Ad hoc (quick)</option>
      <option value="full_council">Full Council</option>
    </select>
  </div>
  <button id="startCouncilBtn" onclick="startCouncil()">Start Council</button>
</div>

<div class="card">
  <h2>Mentor Roster</h2>
  <div class="mentor-grid" id="mentorGrid"></div>
</div>

<div class="card">
  <h2>Council History</h2>
  <div class="session-list" id="councilHistory"></div>
  <div class="empty" id="historyEmpty">No council sessions yet.</div>
</div>

<div class="toast" id="toast"></div>

<script>
async function loadMentors() {
  try {
    const r = await fetch('/api/councils/mentors');
    const d = await r.json();
    const mentors = d.mentors || [];
    const grid = document.getElementById('mentorGrid');
    if (!mentors.length) {
      grid.innerHTML = '<div class="empty">Use Copilot: @gandhi or @marcus_aurelius to chat with mentors.</div>';
      return;
    }
    grid.innerHTML = mentors.map(m =>
      '<div class="mentor-card"><strong>' + esc(m.name) + '</strong><div style="color:var(--muted);font-size:0.85em;margin-top:4px">' + esc(m.archetype || '') + '</div></div>'
    ).join('');
  } catch(e) {}
}

async function loadHistory() {
  try {
    const r = await fetch('/api/councils/sessions');
    const d = await r.json();
    const sessions = d.sessions || [];
    const list = document.getElementById('councilHistory');
    const empty = document.getElementById('historyEmpty');
    if (!sessions.length) {
      list.innerHTML = '';
      empty.style.display = 'block';
      return;
    }
    empty.style.display = 'none';
    list.innerHTML = sessions.map(s =>
      '<div class="session-item" onclick="viewSession(\'' + s.id + '\')">' +
      '<div>' + esc(s.topic) + ' — ' + (s.council_type || '') + '</div>' +
      '<div style="font-size:0.8em;color:var(--muted);margin-top:4px">' + (s.created_at || '').slice(0, 19) + '</div>' +
      '</div>'
    ).join('');
  } catch(e) {}
}

function viewSession(id) {
  showToast('Session detail coming soon. Use Copilot for now.');
}

async function startCouncil() {
  const topic = document.getElementById('councilTopic').value.trim();
  const councilType = document.getElementById('councilType').value;
  if (!topic) { showToast('Enter a topic'); return; }
  const btn = document.getElementById('startCouncilBtn');
  btn.disabled = true;
  try {
    const r = await fetch('/api/councils/start', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({topic, council_type: councilType}),
    });
    const d = await r.json();
    if (d.ok) {
      showToast('Council started! Use Copilot to continue the conversation.');
      loadHistory();
      document.getElementById('councilTopic').value = '';
    } else {
      showToast('Error: ' + (d.error || 'Failed'));
    }
  } catch(e) {
    showToast('Error: ' + e.message);
  }
  btn.disabled = false;
}

function showToast(msg) {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 2500);
}

function esc(s) { const d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }

loadMentors();
loadHistory();
</script>
</body>
</html>
"""

_PERSONAS_HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Personas — Vastian Network</title>
<style>
  __THEME_CSS__
  * { margin: 0; padding: 0; box-sizing: border-box; }
  html, body { height: 100%; }
  body { font-family: 'Segoe UI', system-ui, sans-serif; background: var(--bg); color: var(--text); display: flex; flex-direction: column; }
  .tab-bar { display: flex; gap: 0; border-bottom: 1px solid var(--border); padding: 0 16px; }
  .tab-btn { padding: 12px 20px; background: none; border: none; color: var(--muted); cursor: pointer; font: inherit; font-size: 0.9em; border-bottom: 2px solid transparent; }
  .tab-btn:hover { color: var(--text); }
  .tab-btn.active { color: var(--accent); border-bottom-color: var(--accent); }
  .tab-content { flex: 1; display: none; min-height: 0; }
  .tab-content.active { display: flex; flex-direction: column; }
  .tab-content iframe { flex: 1; width: 100%; border: none; }
  .empty-tab { flex: 1; padding: 24px; color: var(--muted); text-align: center; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; }
</style>
</head>
<body>
<div class="tab-bar">
  <button class="tab-btn active" onclick="switchTab('radar')">Radar Chart</button>
  <button class="tab-btn" onclick="switchTab('roleplay')">Roleplay</button>
  <button class="tab-btn" onclick="switchTab('activities')">Activities</button>
  <button class="tab-btn" onclick="switchTab('challenges')">Challenges</button>
</div>

<div class="tab-content active" id="tab-radar">
  <iframe src="/persona" title="Persona Radar Chart"></iframe>
</div>

<div class="tab-content" id="tab-roleplay">
  <div class="empty-tab">
    <p>Interactive roleplay led by your persona allies. Story-driven scenarios from your personal growth journey.</p>
    <p>Use Copilot: <code>@adrian /persona</code> to start a persona session.</p>
  </div>
</div>

<div class="tab-content" id="tab-activities">
  <div class="empty-tab">
    <p>Shorter exercises from Ojas activities (9 types, 350+ activities).</p>
    <p>Coming soon.</p>
  </div>
</div>

<div class="tab-content" id="tab-challenges">
  <div class="empty-tab">
    <p>Longer scenario challenges from Ojas (700+ challenges, choice-based).</p>
    <p>Coming soon.</p>
  </div>
</div>

<script>
function switchTab(tab) {
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  document.querySelectorAll('.tab-content').forEach(t => t.classList.remove('active'));
  document.querySelector('[onclick="switchTab(\'' + tab + '\')"]').classList.add('active');
  document.getElementById('tab-' + tab).classList.add('active');
}
</script>
</body>
</html>
"""
