import React, { useState } from 'react';
import {
  View, Text, ScrollView, TouchableOpacity, StyleSheet, Linking, Image,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useBooking } from '../context/BookingContext';
import { COLORS, FONTS, FONT_SIZE, SPACING } from '../theme';
import { blogPostsData } from '../data/blog';
import { BlogPost } from '../types';

const logoImg = require('../assets/images/logo.jpg');

export default function BlogScreen() {
  const [selected, setSelected] = useState<BlogPost>(blogPostsData[0]);
  const { openBookingModal } = useBooking();
  const openWhatsApp = () => Linking.openURL('https://wa.me/250790000000');

  // Render plain-text blog content with section headings
  const renderContent = (text: string) => {
    return text.split('\n').filter(line => line.trim()).map((line, i) => {
      const trimmed = line.trim();
      if (trimmed === '---') {
        return <View key={i} style={styles.contentDivider} />;
      }
      // ALL CAPS lines are section headings
      if (trimmed === trimmed.toUpperCase() && trimmed.length > 4 && !trimmed.match(/^\d/)) {
        return (
          <Text key={i} style={styles.contentHeading}>{trimmed}</Text>
        );
      }
      // Numbered list items
      if (/^\d+\./.test(trimmed)) {
        const text = trimmed.replace(/^\d+\.\s*/, '');
        const num  = trimmed.match(/^(\d+\.)/)?.[1] ?? '•';
        return (
          <View key={i} style={styles.listRow}>
            <Text style={styles.listNum}>{num}</Text>
            <Text style={styles.listText}>{text}</Text>
          </View>
        );
      }
      return <Text key={i} style={styles.contentPara}>{trimmed}</Text>;
    });
  };

  return (
    <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>

      {/* Header */}
      <View style={styles.pageHeader}>
        <Text style={styles.overline}>Health Library & Insights</Text>
        <Text style={styles.pageTitle}>Blog & Articles</Text>
        <Text style={styles.pageSubtitle}>
          Insights, self-regulation tips, and resources for mental well-being.
        </Text>
        <View style={styles.divider} />
      </View>

      {/* Article Selector (sidebar becomes top list on mobile) */}
      <View style={styles.sidebarSection}>
        <Text style={styles.sidebarHeading}>Recent Articles</Text>
        {blogPostsData.map(post => (
          <TouchableOpacity
            key={post.id}
            style={[styles.articleBtn, selected.id === post.id && styles.articleBtnActive]}
            onPress={() => setSelected(post)}
          >
            <Text style={styles.articleDate}>{post.date}</Text>
            <Text style={styles.articleTitle}>{post.title}</Text>
            <Text style={styles.articleExcerpt} numberOfLines={2}>{post.excerpt}</Text>
          </TouchableOpacity>
        ))}
      </View>

      {/* Active Article */}
      <View style={styles.articleSection}>

        {/* Tags */}
        <View style={styles.tagsRow}>
          {selected.tags.map((tag, i) => (
            <View key={i} style={styles.tag}>
              <Text style={styles.tagText}>{tag}</Text>
            </View>
          ))}
        </View>

        {/* Title */}
        <Text style={styles.articleHeading}>{selected.title}</Text>

        {/* Meta */}
        <View style={styles.metaRow}>
          <Ionicons name="person-outline" size={13} color={COLORS.slate400} />
          <Text style={styles.metaText}>By Manuel Haeussler</Text>
          <Text style={styles.metaDot}>·</Text>
          <Ionicons name="calendar-outline" size={13} color={COLORS.slate400} />
          <Text style={styles.metaText}>{selected.date}</Text>
          <Text style={styles.metaDot}>·</Text>
          <Ionicons name="time-outline" size={13} color={COLORS.slate400} />
          <Text style={styles.metaText}>7 min read</Text>
        </View>

        {/* Excerpt callout */}
        <View style={styles.excerptBox}>
          <Text style={styles.excerptText}>"{selected.excerpt}"</Text>
        </View>

        {/* Content */}
        <View style={styles.contentBody}>
          {renderContent(selected.content)}
        </View>

        {/* Bottom CTA */}
        <View style={styles.ctaBox}>
          <Text style={styles.ctaTitle}>Wrestling with sleeping difficulties?</Text>
          <Text style={styles.ctaBody}>
            If you are ready to break the cycle of exhaustion and build unwavering trust in your body's ability to heal and rest, let's work together.
          </Text>
          <View style={styles.rowBtns}>
            <TouchableOpacity style={styles.btnDark} onPress={openBookingModal}>
              <Text style={styles.btnDarkText}>Book FREE Call</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.btnOutline} onPress={openWhatsApp}>
              <Ionicons name="chatbubble-ellipses-outline" size={13} color={COLORS.slate600} />
              <Text style={styles.btnOutlineText}>WhatsApp</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>

      {/* Author Card */}
      <View style={styles.authorCard}>
        <Image source={logoImg} style={styles.authorImg} resizeMode="cover" />
        <Text style={styles.authorName}>YOUR WAVE Practitioner</Text>
        <Text style={styles.authorRole}>Manuel Haeussler</Text>
        <Text style={styles.authorBio}>
          Sharing evidence-based knowledge on trauma recovery, sleep science, mindfulness, and the subconscious mind.
        </Text>
      </View>

    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container:       { flex: 1, backgroundColor: COLORS.white },
  pageHeader:      { padding: SPACING.lg, paddingVertical: SPACING.xl, gap: SPACING.sm, backgroundColor: COLORS.slate50, borderBottomWidth: 1, borderBottomColor: COLORS.slate200 },
  overline:        { fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs, color: COLORS.slate400, fontWeight: '700', textTransform: 'uppercase', letterSpacing: 3 },
  pageTitle:       { fontFamily: FONTS.heading, fontSize: FONT_SIZE.xxl, fontWeight: '900', color: COLORS.slate900, textTransform: 'uppercase', letterSpacing: -0.5 },
  pageSubtitle:    { fontFamily: FONTS.serif, fontSize: FONT_SIZE.base, color: COLORS.slate500, fontStyle: 'italic' },
  divider:         { width: 48, height: 2, backgroundColor: COLORS.slate900 },
  sidebarSection:  { backgroundColor: COLORS.slate50, borderBottomWidth: 1, borderBottomColor: COLORS.slate200, padding: SPACING.lg, gap: SPACING.sm },
  sidebarHeading:  { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xxs, color: COLORS.slate900, textTransform: 'uppercase', letterSpacing: 2, paddingBottom: SPACING.sm, borderBottomWidth: 1, borderBottomColor: COLORS.slate200 },
  articleBtn:      { padding: SPACING.sm + 2, borderWidth: 1, borderColor: 'transparent', gap: 3 },
  articleBtnActive:{ backgroundColor: COLORS.white, borderColor: COLORS.slate900 },
  articleDate:     { fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs, color: COLORS.slate400, fontWeight: '700', textTransform: 'uppercase', letterSpacing: 1 },
  articleTitle:    { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.sm, color: COLORS.slate900, textTransform: 'uppercase', letterSpacing: 0.5, lineHeight: 18 },
  articleExcerpt:  { fontFamily: FONTS.serif, fontSize: FONT_SIZE.xxs, color: COLORS.slate500, lineHeight: 16 },
  articleSection:  { padding: SPACING.lg, paddingVertical: SPACING.xl, gap: SPACING.md },
  tagsRow:         { flexDirection: 'row', flexWrap: 'wrap', gap: SPACING.xs },
  tag:             { backgroundColor: COLORS.slate100, paddingHorizontal: SPACING.sm, paddingVertical: 3 },
  tagText:         { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xxs, color: COLORS.slate700, textTransform: 'uppercase', letterSpacing: 1 },
  articleHeading:  { fontFamily: FONTS.heading, fontWeight: '900', fontSize: FONT_SIZE.xxl, color: COLORS.slate900, textTransform: 'uppercase', letterSpacing: -0.5, lineHeight: 34 },
  metaRow:         { flexDirection: 'row', flexWrap: 'wrap', gap: 6, alignItems: 'center', paddingVertical: SPACING.sm, borderTopWidth: 1, borderBottomWidth: 1, borderColor: COLORS.slate100 },
  metaText:        { fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs, color: COLORS.slate400 },
  metaDot:         { fontFamily: FONTS.sans, fontSize: FONT_SIZE.xxs, color: COLORS.slate300 },
  excerptBox:      { borderLeftWidth: 3, borderLeftColor: COLORS.slate900, backgroundColor: COLORS.slate50, padding: SPACING.md },
  excerptText:     { fontFamily: FONTS.serif, fontStyle: 'italic', fontSize: FONT_SIZE.base, color: COLORS.slate700, lineHeight: 24 },
  contentBody:     { gap: SPACING.sm },
  contentHeading:  { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.base, color: COLORS.slate900, textTransform: 'uppercase', letterSpacing: 1, marginTop: SPACING.md, marginBottom: SPACING.xs },
  contentDivider:  { height: 1, backgroundColor: COLORS.slate200, marginVertical: SPACING.md },
  contentPara:     { fontFamily: FONTS.serif, fontSize: FONT_SIZE.sm, color: COLORS.slate600, lineHeight: 22 },
  listRow:         { flexDirection: 'row', gap: SPACING.sm, alignItems: 'flex-start' },
  listNum:         { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.sm, color: COLORS.slate900, minWidth: 20 },
  listText:        { flex: 1, fontFamily: FONTS.serif, fontSize: FONT_SIZE.sm, color: COLORS.slate600, lineHeight: 22 },
  ctaBox:          { backgroundColor: COLORS.slate50, borderWidth: 1, borderColor: COLORS.slate200, padding: SPACING.lg, gap: SPACING.md, marginTop: SPACING.xl },
  ctaTitle:        { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.base, color: COLORS.slate900, textTransform: 'uppercase', letterSpacing: 1 },
  ctaBody:         { fontFamily: FONTS.serif, fontSize: FONT_SIZE.sm, color: COLORS.slate500, lineHeight: 20 },
  rowBtns:         { flexDirection: 'row', gap: SPACING.sm },
  btnDark:         { flex: 1, backgroundColor: COLORS.slate900, paddingVertical: SPACING.sm + 4, alignItems: 'center', justifyContent: 'center' },
  btnDarkText:     { color: COLORS.white, fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xxs, textTransform: 'uppercase', letterSpacing: 2 },
  btnOutline:      { flex: 1, borderWidth: 1, borderColor: COLORS.slate200, paddingVertical: SPACING.sm + 4, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 4 },
  btnOutlineText:  { color: COLORS.slate900, fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xxs, textTransform: 'uppercase', letterSpacing: 2 },
  authorCard:      { backgroundColor: COLORS.white, borderTopWidth: 1, borderTopColor: COLORS.slate200, padding: SPACING.lg, paddingVertical: SPACING.xl, alignItems: 'center', gap: SPACING.sm },
  authorImg:       { width: 64, height: 64, borderWidth: 1, borderColor: COLORS.slate200 },
  authorName:      { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.sm, color: COLORS.slate900, textTransform: 'uppercase', letterSpacing: 1 },
  authorRole:      { fontFamily: FONTS.sans, fontWeight: '700', fontSize: FONT_SIZE.xxs, color: COLORS.slate400, textTransform: 'uppercase', letterSpacing: 2 },
  authorBio:       { fontFamily: FONTS.serif, fontSize: FONT_SIZE.xs, color: COLORS.slate500, textAlign: 'center', lineHeight: 18, maxWidth: 280 },
});
