'use client';

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { isAuthenticated, getEmail } from '@/lib/auth';
import { useIsMobile } from '@/lib/useIsMobile';
import AppHeader from '@/components/AppHeader';
import { useTranslation } from '@/lib/i18n';
import { mdComponentsCompact } from '@/lib/mdComponents';

type ReleaseNote = {
  slug: string;
  title: string;
  date: string;
  tag: string;
};

// ─── Helpers ──────────────────────────────────────────────────

// Extract title / date / tag from the leading lines of a markdown release note.
// Expects:  # Investibook v0.2
//           > Released: 2026-03-12
//           > Tag: `investibook/v0.2`
function parseMeta(md: string): { title: string; date: string; tag: string } {
  const lines = md.split('\n');
  const title = lines.find(l => l.startsWith('# '))?.replace(/^#\s+/, '') ?? '';
  const dateLine = lines.find(l => /released:/i.test(l));
  const tagLine = lines.find(l => /^>\s*Tag:/i.test(l));
  const date = dateLine?.replace(/^>?\s*Released:\s*/i, '').trim() ?? '';
  const tag = tagLine?.replace(/^>?\s*Tag:\s*`?/i, '').replace(/`?\s*$/, '').trim() ?? '';
  return { title, date, tag };
}

// Strip the first H1 and its following blockquote (date/tag meta rows) so they
// don't render twice — they're already shown in the styled card header.
function stripHeaderBlock(md: string): string {
  return md
    .replace(/^#[^\n]*\n+/, '')           // remove first H1
    .replace(/^(>\s*[^\n]+\n*)+\n*/, ''); // remove leading blockquote block
}

// ─── Skeleton loader ──────────────────────────────────────────

function Skeleton({ isMobile }: { isMobile: boolean }) {
  return (
    <div style={{ background: '#fff', borderRadius: '14px', border: '1px solid #eee', overflow: 'hidden', marginBottom: '28px' }}>
      <div style={{ padding: isMobile ? '18px 16px' : '22px 28px', borderBottom: '1px solid #f0f0f0', background: '#fafafa' }}>
        <div style={{ height: '24px', width: '200px', background: '#eee', borderRadius: '6px', marginBottom: '12px' }} />
        <div style={{ height: '14px', width: '280px', background: '#f0f0f0', borderRadius: '4px' }} />
      </div>
      <div style={{ padding: isMobile ? '20px 16px' : '24px 28px' }}>
        {[80, 60, 90, 70, 55].map((w, i) => (
          <div key={i} style={{ height: '13px', width: `${w}%`, background: '#f4f4f4', borderRadius: '4px', marginBottom: '10px' }} />
        ))}
      </div>
    </div>
  );
}

// ─── Icons ────────────────────────────────────────────────────

function CalendarIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect width="18" height="18" x="3" y="4" rx="2" ry="2" /><line x1="16" x2="16" y1="2" y2="6" /><line x1="8" x2="8" y1="2" y2="6" /><line x1="3" x2="21" y1="10" y2="10" />
    </svg>
  );
}

function TagIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 2H2v10l9.29 9.29c.94.94 2.48.94 3.42 0l6.58-6.58c.94-.94.94-2.48 0-3.42L12 2Z" /><path d="M7 7h.01" />
    </svg>
  );
}

// ─── Version Card ─────────────────────────────────────────────

function VersionCard({ note, isLatest, isMobile }: { note: ReleaseNote; isLatest: boolean; isMobile: boolean }) {
  const { t } = useTranslation();
  const { slug, title, date, tag } = note;
  const [markdown, setMarkdown] = useState<string | null>(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    fetch(`/release-notes/${slug}.md`, { cache: 'force-cache' })
      .then(r => {
        if (!r.ok) {
          throw new Error('failed to load markdown');
        }
        return r.text();
      })
      .then(setMarkdown)
      .catch(() => {
        setError(true);
      });
  }, [slug]);

  if (error) {
    return (
      <div style={{ background: '#fff', borderRadius: '14px', border: '1px solid #fee2e2', overflow: 'hidden', marginBottom: '28px' }}>
        <div style={{ padding: isMobile ? '18px 16px 16px' : '22px 28px 18px', borderBottom: '1px solid #f0f0f0', background: '#fafafa' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap', marginBottom: '10px' }}>
            <span style={{ fontSize: isMobile ? '20px' : '24px', fontWeight: 800, color: '#1a1a2e', letterSpacing: '-0.5px' }}>
              {title || slug}
            </span>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: '14px', alignItems: 'center' }}>
            {date && (
              <span style={{ display: 'flex', alignItems: 'center', gap: '5px', fontSize: '13px', color: '#888' }}>
                <CalendarIcon /> {t('releaseNotes.released', { date })}
              </span>
            )}
            {tag && (
              <span style={{ display: 'flex', alignItems: 'center', gap: '5px', fontSize: '12px', color: '#888', fontFamily: 'monospace', background: '#f0f0f8', padding: '2px 8px', borderRadius: '5px' }}>
                <TagIcon /> {tag}
              </span>
            )}
          </div>
        </div>
        <div style={{ padding: isMobile ? '16px 16px 28px' : '20px 28px 32px', fontSize: '14px', color: '#b91c1c' }}>
          {t('releaseNotes.cardLoadFailed')}
        </div>
      </div>
    );
  }

  if (markdown === null) {
    return <Skeleton isMobile={isMobile} />;
  }

  return (
    <div style={{
      background: '#fff', borderRadius: '14px',
      border: `1px solid ${isLatest ? '#c7c9f0' : '#eee'}`,
      overflow: 'hidden', marginBottom: '28px',
      boxShadow: isLatest ? '0 2px 12px rgba(92,95,188,0.08)' : 'none',
    }}>
      {/* ── Card header ── */}
      <div style={{
        padding: isMobile ? '18px 16px 16px' : '22px 28px 18px',
        borderBottom: '1px solid #f0f0f0',
        background: isLatest ? 'linear-gradient(135deg, #f5f5fd 0%, #ffffff 100%)' : '#fafafa',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'wrap', marginBottom: '10px' }}>
          <span style={{ fontSize: isMobile ? '20px' : '24px', fontWeight: 800, color: '#1a1a2e', letterSpacing: '-0.5px' }}>
            {title || parseMeta(markdown).title || slug}
          </span>
          {isLatest && (
            <span style={{ fontSize: '11px', fontWeight: 700, color: '#fff', background: 'linear-gradient(135deg, #5c5fbc, #7c7fdc)', padding: '3px 10px', borderRadius: '20px', letterSpacing: '0.3px' }}>
              {t('releaseNotes.latest')}
            </span>
          )}
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '14px', alignItems: 'center' }}>
          {date && (
            <span style={{ display: 'flex', alignItems: 'center', gap: '5px', fontSize: '13px', color: '#888' }}>
              <CalendarIcon /> Released {date}
            </span>
          )}
          {tag && (
            <span style={{ display: 'flex', alignItems: 'center', gap: '5px', fontSize: '12px', color: '#888', fontFamily: 'monospace', background: '#f0f0f8', padding: '2px 8px', borderRadius: '5px' }}>
              <TagIcon /> {tag}
            </span>
          )}
        </div>
      </div>

      {/* ── Rendered markdown ── */}
      <div style={{ padding: isMobile ? '16px 16px 28px' : '20px 28px 32px' }}>
        <ReactMarkdown remarkPlugins={[remarkGfm]} components={mdComponentsCompact(isMobile)}>
          {stripHeaderBlock(markdown)}
        </ReactMarkdown>
      </div>
    </div>
  );
}


// ─── Main Page ───────────────────────────────────────────────

export default function ReleaseNotesPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const isMobile = useIsMobile();
  const [userEmail, setUserEmail] = useState<string | null>(null);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [releaseNotes, setReleaseNotes] = useState<ReleaseNote[] | null>(null);
  const [loadError, setLoadError] = useState(false);

  useEffect(() => {
    if (!isAuthenticated()) {
      router.replace(`/login?redirect=${encodeURIComponent(window.location.pathname + window.location.search)}`);
      return;
    }
    setUserEmail(getEmail());
  }, [router]);

  const handleLogout = async () => {
    const { logout } = await import('@/lib/auth');
    await logout();
    router.replace('/login');
  };

  useEffect(() => {
    if (!isAuthenticated()) {
      return;
    }

    fetch('/release-notes/manifest', { cache: 'no-store' })
      .then(r => {
        if (!r.ok) {
          throw new Error('failed to load release notes');
        }
        return r.json();
      })
      .then((data: { notes?: ReleaseNote[] }) => {
        setLoadError(false);
        setReleaseNotes(Array.isArray(data.notes) ? data.notes : []);
      })
      .catch(() => {
        setReleaseNotes([]);
        setLoadError(true);
      });
  }, []);

  return (
    <div style={{ minHeight: '100vh', background: '#f8f9fa' }}>
      <AppHeader
        activePage="release-notes"
        email={userEmail}
        isMobile={isMobile}
        onSettings={() => setSettingsOpen(true)}
        onLogout={handleLogout}
      />

      <div style={{ maxWidth: '900px', margin: '0 auto', padding: isMobile ? '20px 16px' : '32px 40px' }}>

        {/* Page header */}
        <div style={{ marginBottom: '32px' }}>
          <h1 style={{ fontSize: isMobile ? '22px' : '28px', fontWeight: 700, color: '#1a1a2e', margin: 0 }}>
            {t('releaseNotes.title')}
          </h1>
          <p style={{ fontSize: '14px', color: '#999', margin: '8px 0 0 0' }}>
            {t('releaseNotes.subtitle')}
          </p>
        </div>

        {/* Version cards */}
        {releaseNotes === null && (
          <>
            <Skeleton isMobile={isMobile} />
            <Skeleton isMobile={isMobile} />
          </>
        )}

        {loadError && (
          <div style={{ fontSize: '14px', color: '#b91c1c', background: '#fef2f2', border: '1px solid #fecaca', borderRadius: '12px', padding: '14px 16px' }}>
            {t('releaseNotes.loadFailed')}
          </div>
        )}

        {releaseNotes?.map((note, i) => (
          <VersionCard key={note.slug} note={note} isMobile={isMobile} isLatest={i === 0} />
        ))}
      </div>

      {settingsOpen && <SettingsModalWrapper open={settingsOpen} onClose={() => setSettingsOpen(false)} />}
    </div>
  );
}

function SettingsModalWrapper({ open, onClose }: { open: boolean; onClose: () => void }) {
  const SettingsModal = require('@/components/SettingsModal').default;
  return <SettingsModal open={open} onClose={onClose} />;
}
