// PRE — Dashboard, Tutorial & Onboarding
(() => {
  const escapeHtml = PRE.escapeHtml;

  function getTutorialData() {
    const isMac = window.PRE_PLATFORM === 'macos';
    const isWin = window.PRE_PLATFORM === 'windows';
    return [
      {
        icon: '\u{1F4AC}', title: 'Getting Started', category: 'basics',
        tip: 'PRE auto-titles sessions and remembers context within a conversation.',
        prompts: [
          "What can you help me with? Give me a quick overview of your capabilities.",
          isMac ? "What's running on my Mac right now? Show me the top 10 processes by CPU usage."
                : "What's running on my PC right now? Show me the top 10 processes by CPU usage.",
          "Summarize what's in my Downloads folder.",
          "What day of the week was July 4, 1776?",
        ]
      },
      {
        icon: '\u{1F4C1}', title: 'File Operations', category: 'files',
        tip: 'PRE can read, write, search, and edit any file on your system.',
        prompts: [
          "Find all Python files in my home directory that import pandas.",
          isMac ? "Read my ~/.zshrc and suggest improvements for performance."
                : "Read my PowerShell profile and suggest improvements for performance.",
          "Search my Documents folder for any file mentioning \"quarterly review\".",
          "Find every TODO comment in this project and create a summary.",
        ]
      },
      {
        icon: isMac ? '\u{1F34E}' : '\u{1F5A5}\uFE0F', title: isMac ? 'Native macOS' : 'Native Apps', category: 'native',
        tip: isMac ? 'Works with any email/calendar provider configured on your Mac \u2014 no API keys needed.'
                   : 'Works with Outlook for mail, calendar, contacts, reminders, and local notes.',
        prompts: [
          "What's on my calendar today? Include meeting links if available.",
          "Check my email for anything from my boss in the last 3 days.",
          "Remind me to submit the expense report by Friday at 5pm.",
          "Search my notes for anything about the API migration.",
          isMac ? "Find all PDF documents on my Mac that contain \"budget proposal\"."
                : "Find all PDF documents in my Documents folder that contain \"budget proposal\".",
        ]
      },
      {
        icon: '\u{1F5B1}\uFE0F', title: 'Desktop Automation', category: 'computer',
        tip: 'PRE sees your screen and operates any app via mouse and keyboard.',
        prompts: [
          "Take a screenshot and describe what's on my screen.",
          isMac ? "Open System Settings and navigate to the Wi-Fi section."
                : "Open Settings and navigate to the Wi-Fi section.",
          isMac ? "Press Cmd+Space to open Spotlight, type \"Activity Monitor\", and press Enter."
                : "Press Win+S to open Search, type \"Task Manager\", and press Enter.",
          "Start recording a workflow called \"morning-setup\".",
        ]
      },
      {
        icon: '\u{1F310}', title: 'Browser & Web', category: 'browser',
        tip: 'Built-in headless Chrome for scraping, browsing, and form filling.',
        prompts: [
          "Search the web for the latest AI news.",
          "Open the browser, go to news.ycombinator.com, and tell me the top 5 stories.",
          "Navigate to Wikipedia and find today's featured article.",
        ]
      },
      {
        icon: '\u{1F9E0}', title: 'Memory & RAG', category: 'memory',
        tip: 'Memories persist across sessions. RAG searches documents by meaning.',
        prompts: [
          "Remember that our team standup is at 9:15 AM Pacific every weekday.",
          "Search my memories for anything about deployment procedures.",
          isMac ? "Index my ~/Documents/notes folder and call the index \"my-notes\"."
                : "Index my Documents\\notes folder and call the index \"my-notes\".",
          "Search the \"my-notes\" index for anything about project deadlines.",
        ]
      },
      {
        icon: '\u23F0', title: 'Scheduling & Triggers', category: 'automation',
        tip: 'Cron jobs run in the background, even when you\'re away.',
        prompts: [
          "Schedule a daily morning briefing at 8am that checks my calendar and unread emails. Run it Monday through Friday.",
          isMac ? "Create a trigger that watches ~/Downloads for new PDFs and summarizes them."
                : "Create a trigger that watches my Downloads folder for new PDFs and summarizes them.",
          "List all my scheduled jobs and their next run times.",
        ]
      },
      {
        icon: '\u{1F916}', title: 'Sub-Agents', category: 'agents',
        tip: 'Agents work autonomously, each with their own session and tools.',
        prompts: [
          "Spawn agents to research PostgreSQL vs MySQL for a high-write workload, then compare their findings.",
          "Spawn an agent to read all README files in my projects directory and summarize each project.",
        ]
      },
      {
        icon: '\u2601\uFE0F', title: 'Cloud Integrations', category: 'cloud',
        tip: 'Configure integrations in Settings (gear icon). 15 services available.',
        prompts: [
          "Show me all Jira tickets assigned to me that are In Progress.",
          "Search Slack for messages about the production deployment in the last 24 hours.",
          "List my open pull requests on GitHub.",
          "What Zoom meetings do I have scheduled this week?",
        ]
      },
      {
        icon: '\u{1F9E9}', title: 'Smart Features', category: 'smart',
        tip: 'Session search, progressive tool loading, and auto-created custom tools.',
        prompts: [
          "Search my past sessions for anything about database migrations.",
          "What tool domains are available? Load the devops tools.",
          "List my custom tools and any auto-created skills.",
        ]
      },
      {
        icon: '\u{1F3A8}', title: 'Artifacts & Exports', category: 'artifacts',
        tip: 'PRE creates interactive HTML documents, reports, and visualizations.',
        prompts: [
          "Create an interactive HTML dashboard showing a sample project timeline with milestones and progress bars.",
          "Build a Pomodoro timer as an HTML artifact with start/pause/reset buttons.",
          "Create a Word document summarizing today's meeting notes with action items.",
        ]
      },
      {
        icon: '\u{1F5BC}\uFE0F', title: 'Image Generation', category: 'image',
        tip: 'Requires ComfyUI running locally. Configure in Settings.',
        prompts: [
          "Generate an image of a mountain landscape at sunset with dramatic clouds.",
          "Create a photorealistic image of a cozy reading nook with warm lighting.",
          "Check if image generation is available on my system.",
        ]
      },
      {
        icon: '\u{1F399}\uFE0F', title: 'Voice Interface', category: 'voice',
        tip: 'All audio is processed locally via Whisper \u2014 nothing leaves your machine.',
        prompts: [
          "Read this aloud: \"Good morning! Here's your daily briefing.\"",
          "What voices are available for text-to-speech?",
        ]
      },
      {
        icon: '\u{1F525}', title: 'Power Workflows', category: 'power',
        tip: 'Combine multiple features into real-world multi-step workflows.',
        prompts: [
          "Check my calendar for today, summarize important unread emails, list my top Jira tickets, and give me a morning briefing.",
          "Index this repository with RAG, then search for the authentication flow and database schema. Give me a developer onboarding summary.",
          "Check disk usage, list top 20 processes by memory, and verify network connectivity. Format as a system health report.",
        ]
      },
    ];
  }

  // Send a tutorial prompt to the chat
  function sendTutorialPrompt(text) {
    const input = document.getElementById('chat-input');
    if (!input) return;
    input.value = text;
    input.style.height = 'auto';
    input.style.height = Math.min(input.scrollHeight, 200) + 'px';
    input.focus();
    // Scroll input into view
    input.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }

  // ── Home screen dashboard ──
  async function renderDashboard() {
    const container = document.getElementById('welcome-dashboard');
    if (!container) return;

    let data;
    try {
      const res = await fetch('/api/dashboard');
      data = await res.json();
    } catch { return; }

    const { calendar, recentSessions, stats } = data;
    if (!calendar.length && !recentSessions.length) {
      container.innerHTML = '';
      return;
    }

    let html = '';

    // Resume banner — show when there's a saved session the user was working in
    try {
      const resumeRaw = localStorage.getItem('pre-resume-session');
      if (resumeRaw) {
        const resume = JSON.parse(resumeRaw);
        const currentSession = sessionStorage.getItem('pre-session') || localStorage.getItem('pre-last-session') || null;
        if (resume.id && resume.id !== currentSession) {
          const ago = PRE.timeAgo(resume.time);
          const name = resume.name || 'your last session';
          html += `<div class="resume-banner" onclick="window.Dashboard.openSession('${escapeHtml(resume.id)}')">`;
          html += `<span class="resume-banner-icon">\u21A9</span>`;
          html += `<span class="resume-banner-text">Continue: <strong>${escapeHtml(name)}</strong></span>`;
          html += `<span class="resume-banner-time">${escapeHtml(ago)}</span>`;
          html += `</div>`;
        }
      }
    } catch {}

    html += '<div class="dashboard-grid">';

    // Calendar column
    html += '<div class="dashboard-card">';
    html += '<div class="dashboard-card-title">Today\'s Schedule</div>';
    if (calendar.length) {
      for (const ev of calendar) {
        html += `<div class="dashboard-event">`;
        html += `<span class="dashboard-event-time">${escapeHtml(ev.start)}</span>`;
        html += `<span class="dashboard-event-title">${escapeHtml(ev.title)}</span>`;
        html += `</div>`;
      }
    } else {
      html += '<div class="dashboard-empty">No events today</div>';
    }
    html += '</div>';

    // Recent sessions + stats column
    html += '<div class="dashboard-card">';
    html += '<div class="dashboard-card-title">Recent Sessions</div>';
    if (recentSessions.length) {
      for (const s of recentSessions) {
        const ago = PRE.timeAgo(s.time);
        html += `<div class="dashboard-session" onclick="window.Dashboard.openSession('${escapeHtml(s.id)}')">`;
        html += `<span class="dashboard-session-name">${escapeHtml(s.name)}</span>`;
        html += `<span class="dashboard-session-time">${escapeHtml(ago)}</span>`;
        html += `</div>`;
      }
    } else {
      html += '<div class="dashboard-empty">No sessions yet</div>';
    }
    // Stats row
    html += '<div class="dashboard-stats">';
    html += `<div class="dashboard-stat"><div class="dashboard-stat-value">${stats.cronJobs}</div><div class="dashboard-stat-label">Cron Jobs</div></div>`;
    html += `<div class="dashboard-stat"><div class="dashboard-stat-value">${stats.connections}</div><div class="dashboard-stat-label">Integrations</div></div>`;
    if (stats.telegram) {
      html += `<div class="dashboard-stat"><div class="dashboard-stat-value dashboard-telegram-active">\u{1F4F1}</div><div class="dashboard-stat-label">Mobile</div></div>`;
    }
    html += '</div>';
    html += '</div>';

    html += '</div>';
    container.innerHTML = html;

    // Fetch and render proactive suggestions below the dashboard
    _renderSuggestions(container);
  }

  async function _renderSuggestions(container) {
    try {
      const res = await fetch('/api/suggestions');
      const suggestions = await res.json();
      if (!suggestions.length) return;

      let html = '<div class="suggestions-row">';
      for (const s of suggestions) {
        const prompt = escapeHtml(s.prompt).replace(/'/g, '&#39;');
        html += `<button class="suggestion-chip" onclick="window.Dashboard.suggest('${prompt}')" title="${escapeHtml(s.text)}">`;
        html += `<span class="suggestion-icon">${s.icon}</span> ${escapeHtml(s.text)}`;
        html += `</button>`;
      }
      html += '</div>';
      container.insertAdjacentHTML('beforeend', html);
    } catch {}
  }

  window.Dashboard = {
    openSession(sessionId) {
      if (sessionId) PRE.emit('navigateSession', sessionId);
    },
    suggest(prompt) {
      if (prompt) {
        const inp = document.getElementById('chat-input');
        if (inp) { inp.value = prompt; inp.dispatchEvent(new Event('input')); }
        document.getElementById('chat-form').dispatchEvent(new Event('submit'));
      }
    },
    refresh() { renderDashboard(); },
  };

  // Render welcome screen — first-run shows workflow templates, returning users see tutorial cards
  async function renderWelcomeTutorial() {
    const container = document.getElementById('welcome-tutorial');
    if (!container) return;

    // Check onboarding state
    let onboardingData = null;
    try {
      const platform = window.PRE_PLATFORM || 'macos';
      const res = await fetch(`/api/onboarding?platform=${platform}`);
      onboardingData = await res.json();
    } catch { /* fall through to tutorials */ }

    if (onboardingData && onboardingData.firstRun) {
      renderWorkflowTemplates(container, onboardingData.workflows);
      return;
    }

    // Returning user — show tutorial cards
    renderTutorialCards(container);
  }

  function renderTutorialCards(container) {
    const data = getTutorialData();
    const showcaseOrder = ['basics', 'native', 'computer', 'memory', 'automation', 'power'];
    const showcase = showcaseOrder
      .map(cat => data.find(t => t.category === cat))
      .filter(Boolean);

    container.innerHTML = showcase.map(t => {
      const prompt = t.prompts[Math.floor(Math.random() * t.prompts.length)];
      return `<div class="tutorial-card" onclick="window.Tutorial.send(this.dataset.prompt)" data-prompt="${escapeHtml(prompt)}">
        <span class="tutorial-card-icon">${t.icon}</span>
        <div class="tutorial-card-title">${escapeHtml(t.title)}</div>
        <div class="tutorial-card-prompt">${escapeHtml(prompt)}</div>
      </div>`;
    }).join('');
  }

  function renderWorkflowTemplates(container, workflows) {
    let html = '<div class="workflow-header">';
    html += '<div class="workflow-header-title">Get started with a setup workflow</div>';
    html += '<div class="workflow-header-sub">These one-click templates configure PRE for daily use. Pick one to get going, or <a href="#" onclick="event.preventDefault();window.Onboarding.skip()" style="color:var(--primary)">skip to explore on your own</a>.</div>';
    html += '</div>';

    html += '<div class="workflow-grid">';
    for (const wf of workflows) {
      html += `<div class="tutorial-card workflow-card" onclick="window.Onboarding.run('${escapeHtml(wf.id)}')" data-workflow-id="${escapeHtml(wf.id)}">`;
      html += `<span class="tutorial-card-icon">${wf.icon}</span>`;
      html += `<div class="tutorial-card-title">${escapeHtml(wf.title)}</div>`;
      html += `<div class="tutorial-card-prompt">${escapeHtml(wf.description)}</div>`;
      html += `</div>`;
    }
    html += '</div>';

    container.innerHTML = html;
  }

  // Full tutorial panel (opened from sidebar or welcome)
  function openTutorialPanel() {
    const panel = document.getElementById('right-panel');
    const title = document.getElementById('panel-title');
    const content = document.getElementById('panel-content');
    title.textContent = 'Tutorial';
    panel.classList.remove('hidden');

    let html = '<div style="padding:0 4px">';
    html += '<p style="font-size:0.78rem;color:var(--text-muted);margin-bottom:16px;line-height:1.5">Click any prompt below to load it into the chat input. These examples showcase every major feature of PRE.</p>';

    for (const cat of getTutorialData()) {
      html += `<div class="tutorial-category">`;
      html += `<div class="tutorial-category-title">${cat.icon} ${escapeHtml(cat.title)}</div>`;
      for (const prompt of cat.prompts) {
        html += `<div class="tutorial-prompt-item" onclick="window.Tutorial.send(this.dataset.prompt)" data-prompt="${escapeHtml(prompt)}">${escapeHtml(prompt)}</div>`;
      }
      html += `<div class="tutorial-tip">${escapeHtml(cat.tip)}</div>`;
      html += '</div>';
    }

    html += '</div>';
    content.innerHTML = html;
  }

  // Global Tutorial API
  window.Tutorial = {
    send(prompt) {
      if (prompt) sendTutorialPrompt(prompt);
    },
    open() {
      openTutorialPanel();
    },
    _renderWelcome() {
      renderWelcomeTutorial();
    },
  };

  // Global Onboarding API
  window.Onboarding = {
    async run(workflowId) {
      // Find the workflow prompt
      try {
        const platform = window.PRE_PLATFORM || 'macos';
        const res = await fetch(`/api/onboarding?platform=${platform}`);
        const data = await res.json();
        const wf = data.workflows.find(w => w.id === workflowId);
        if (!wf) return;

        // Mark workflow as run (marks onboarding complete)
        await fetch('/api/onboarding/workflow', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ workflowId }),
        });

        // Send the prompt and submit
        sendTutorialPrompt(wf.prompt);
        document.getElementById('chat-form').dispatchEvent(new Event('submit'));
      } catch (err) {
        console.error('Onboarding workflow error:', err);
      }
    },
    async skip() {
      try {
        await fetch('/api/onboarding/dismiss', { method: 'POST' });
      } catch {}
      // Re-render welcome screen with tutorial cards
      const container = document.getElementById('welcome-tutorial');
      if (container) renderTutorialCards(container);
    },
  };

  // Render welcome screen on load
  renderWelcomeTutorial();
  renderDashboard();
})();
