import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Shield, Users, TrendingUp, Clock, DollarSign, MapPin, Phone, Mail, ArrowRight, CheckCircle, Bot, MessageCircle } from 'lucide-react';
import Layout from '@/components/Layout';
import HeroSlider from '@/components/HeroSlider';
import { Card, CardContent } from '@/components/ui/card';
import ChatbotHint from '@/components/ChatbotHint';

type FocusTopicId = 'health' | 'risk' | 'retirement';

const Senioren = () => {
  const { t } = useTranslation('senioren');
  const navigate = useNavigate();
  const baseUrl = import.meta.env.BASE_URL;
  const assetUrl = (fileName: string) => `${baseUrl}${encodeURI(fileName)}`;
  const [focusTopics, setFocusTopics] = useState<Array<{ id: FocusTopicId; title: string; href: string; image: string }>>([]);

  useEffect(() => {
    const pool = [
      { id: 'health' as const, title: t('focus.items.health', 'Gesundheitsvorsorge'), href: '/senioren-gesundheitsvorsorge', image: assetUrl('iStock-957363908.jpg') },
      { id: 'risk' as const, title: t('focus.items.risk', 'Risikoschutz'), href: '/senioren-risikoschutz', image: assetUrl('iStock-970876204.jpg') },
      { id: 'retirement' as const, title: t('focus.items.retirement', 'Altersvorsorge'), href: '/senioren-altersvorsorge', image: assetUrl('Fotolia_67327775_XS.jpg') },
    ];

    setFocusTopics(
      [...pool].sort((a, b) => a.title.localeCompare(b.title, 'de', { sensitivity: 'base' }))
    );
  }, [t]);

  const detailsLabel = t('details.label', 'Details:');
  const healthLinksRaw = t('details.health.links', { returnObjects: true }) as unknown;
  const healthLinks = Array.isArray(healthLinksRaw)
    ? (healthLinksRaw as Array<{ title: string; href: string }>)
    : [
        { title: 'Krankenversicherung', href: '/senioren-gesundheitsvorsorge' },
        { title: 'Pflegeversicherung', href: '/senioren-gesundheitsvorsorge' },
        { title: 'Unfallversicherung', href: '/senioren-gesundheitsvorsorge' },
      ];

  const riskLinksRaw = t('details.risk.links', { returnObjects: true }) as unknown;
  const riskLinks = Array.isArray(riskLinksRaw)
    ? (riskLinksRaw as Array<{ title: string; href: string }>)
    : [
        { title: 'Sterbegeldversicherung', href: '/senioren-risikoschutz' },
        { title: 'Hausratversicherung', href: '/senioren-risikoschutz' },
        { title: 'Tierhalterhaftpflicht', href: '/senioren-risikoschutz' },
      ];

  const retirementLinksRaw = t('details.retirement.links', { returnObjects: true }) as unknown;
  const retirementLinks = Array.isArray(retirementLinksRaw)
    ? (retirementLinksRaw as Array<{ title: string; href: string }>)
    : [
        { title: 'Riester-Rente', href: '/senioren-altersvorsorge' },
        { title: 'Rürup-Rente', href: '/senioren-altersvorsorge' },
        { title: 'Betriebliche Altersvorsorge', href: '/senioren-altersvorsorge' },
      ];

  const benefitsRaw = t('benefits.items', { returnObjects: true }) as unknown;
  const benefits = Array.isArray(benefitsRaw) ? (benefitsRaw as Array<{ title: string; desc: string }>) : [];
  const benefitIcons = [Shield, Users, TrendingUp, Clock, DollarSign, MapPin];

  return (
    <Layout>
      <HeroSlider
        slides={[
          {
            id: 'senioren-1',
            kicker: t('hero.kicker', 'Versicherungen für Senioren'),
            title: t('hero.title', 'Sicherheit und Wohlbefinden im Alter.'),
            subtitle: t(
              'hero.subtitle',
              'Maßgeschneiderte Lösungen für Ihre Lebensphase – von der Gesundheitsvorsorge bis zur Altersvorsorge.'
            ),
            imageUrl: assetUrl('Fotolia_67327775_XS.jpg'),
            imagePosition: 'center 35%',
            ctas: [
              { label: t('hero.primaryCta', 'Jetzt beraten lassen'), href: '/contact' },
              { label: t('hero.secondaryCta', 'Alle Leistungen'), href: '/leistungen' },
            ],
          },
        ]}
      />

      {/* Senioren Themen */}
      <section className="py-16 bg-gradient-to-br from-gray-50 to-blue-50">
        <div className="container mx-auto px-4">
          <div className="text-center mb-12">
            <h2 className="text-4xl md:text-5xl font-bold text-gray-900 mb-4">
              {t('topics.title', 'Themen für Senioren')}
            </h2>
            <p className="text-xl text-gray-600 max-w-3xl mx-auto">
              {t('topics.subtitle', 'Die wichtigsten Lösungen für Ihre Lebensphase')}
            </p>
          </div>

          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto">
            {focusTopics.map((item) => (
              <div
                key={`${item.href}-${item.title}`}
                className="group cursor-pointer transform transition-all duration-300 hover:scale-[1.04]"
                role="link"
                tabIndex={0}
                onClick={() => navigate(item.href)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') navigate(item.href);
                }}
              >
                <div className="relative h-44 md:h-50 overflow-hidden rounded-xl shadow-lg group-hover:shadow-2xl transition-shadow duration-300">
                  <div
                    className="absolute inset-0 bg-cover bg-center transform transition-transform duration-500 group-hover:scale-[1.08]"
                    style={{ backgroundImage: `url(${item.image})` }}
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent" />
                  
                  {/* Overlay mit Titel */}
                  <div className="absolute bottom-0 left-0 right-0 p-4 text-white">
                    <div className="text-xl font-bold">{item.title.replace('Versicherung', '').trim()}</div>
                  </div>
                </div>
                
                {/* Links unter dem Bild */}
                <div className="mt-4 p-4 bg-white rounded-lg shadow-md">
                  {item.id === 'health' && (
                    <div className="space-y-2">
                      <div className="text-xs uppercase tracking-wide text-gray-500 font-semibold mb-3">{detailsLabel}</div>
                      <div className="grid grid-cols-1 gap-2">
                        {healthLinks.map((link) => (
                          <Link 
                            key={`${link.href}-${link.title}`}
                            to={link.href} 
                            className="text-blue-600 hover:text-blue-800 hover:underline text-sm font-medium transition-colors duration-200 flex items-center group"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <span className="w-2 h-2 bg-blue-600 rounded-full mr-2 group-hover:bg-blue-800 transition-colors"></span>
                            {link.title}
                          </Link>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Zusätzliche Links unter dem Bild für Risikoschutz */}
                  {item.id === 'risk' && (
                    <div className="space-y-2">
                      <div className="text-xs uppercase tracking-wide text-gray-500 font-semibold mb-3">{detailsLabel}</div>
                      <div className="grid grid-cols-1 gap-2">
                        {riskLinks.map((link) => (
                          <Link 
                            key={`${link.href}-${link.title}`}
                            to={link.href} 
                            className="text-blue-600 hover:text-blue-800 hover:underline text-sm font-medium transition-colors duration-200 flex items-center group"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <span className="w-2 h-2 bg-blue-600 rounded-full mr-2 group-hover:bg-blue-800 transition-colors"></span>
                            {link.title}
                          </Link>
                        ))}
                      </div>
                    </div>
                  )}

                  {/* Zusätzliche Links unter dem Bild für Altersvorsorge */}
                  {item.id === 'retirement' && (
                    <div className="space-y-2">
                      <div className="text-xs uppercase tracking-wide text-gray-500 font-semibold mb-3">{detailsLabel}</div>
                      <div className="grid grid-cols-1 gap-2">
                        {retirementLinks.map((link) => (
                          <Link 
                            key={`${link.href}-${link.title}`}
                            to={link.href} 
                            className="text-blue-600 hover:text-blue-800 hover:underline text-sm font-medium transition-colors duration-200 flex items-center group"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <span className="w-2 h-2 bg-blue-600 rounded-full mr-2 group-hover:bg-blue-800 transition-colors"></span>
                            {link.title}
                          </Link>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>

          <div className="mt-14">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 max-w-6xl mx-auto items-stretch">
              <Card className="overflow-hidden shadow-lg hover:shadow-2xl transition-shadow rounded-2xl flex flex-col h-full">
                <div className="relative h-44">
                  <div
                    className="absolute inset-0 bg-cover bg-center"
                    style={{ backgroundImage: `url(${assetUrl('iStock-939772870.jpg')})` }}
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/50 via-black/10 to-transparent" />
                </div>
                <CardContent className="p-6 flex-1 flex flex-col">
                    <div className="text-xl font-bold text-gray-900">
                      {t('tiles.sterbegeld.title', 'Sterbegeldversicherung')}
                    </div>
                    <div className="mt-2 text-sm text-gray-600">
                      {t(
                        'tiles.sterbegeld.subtitle',
                        'Für Ihre Liebsten vorsorgen: finanzielle Sicherheit im Todesfall.'
                      )}
                    </div>

                    <div className="mt-5 text-sm text-gray-700">
                      <div className="text-xs uppercase tracking-wide text-gray-500 font-semibold">
                        {t('tiles.sterbegeld.exampleLabel', 'z.B. Beitragsbeispiel')}
                      </div>
                      <div className="mt-2 text-4xl font-bold text-gray-900">
                        {t('tiles.sterbegeld.examplePrice', '40,75€')}
                      </div>
                      <div className="mt-2 text-sm text-gray-700">
                        {t('tiles.sterbegeld.exampleDetails', 'pro Monat für 12.500 € Versicherungssumme')}
                      </div>
                      <ul className="mt-2 list-disc pl-5 text-sm text-gray-700">
                        <li>{t('tiles.sterbegeld.bullet1', 'Männer/Frauen: ab 53 Jahre')}</li>
                      </ul>

                      <div className="mt-4 text-xs uppercase tracking-wide text-gray-500 font-semibold">
                        {t('tiles.sterbegeld.detailsLabel', 'Details:')}
                      </div>
                      <ul className="mt-2 space-y-1 text-sm text-gray-700">
                        <li>{t('tiles.sterbegeld.detailsItems.0', 'Sterbegeldversicherung')}</li>
                        <li>{t('tiles.sterbegeld.detailsItems.1', 'Bestattungsvorsorge')}</li>
                        <li>{t('tiles.sterbegeld.detailsItems.2', 'Risikolebensversicherung')}</li>
                      </ul>
                    </div>

                    <div className="flex-1" />

                    <Button asChild className="w-full mt-6 bg-red-900 hover:bg-red-950 rounded-full">
                      <Link to="/senioren-sterbegeldversicherung">
                        {t('tiles.sterbegeld.cta', 'Jetzt informieren')}
                        <ArrowRight className="ml-2 h-4 w-4" />
                      </Link>
                    </Button>
                  </CardContent>
                </Card>

              <Card className="overflow-hidden shadow-lg hover:shadow-2xl transition-shadow rounded-2xl flex flex-col h-full">
                <div className="relative h-44">
                  <div
                    className="absolute inset-0 bg-cover bg-center"
                    style={{ backgroundImage: `url(${assetUrl('head_brennen.jpg')})` }}
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/50 via-black/10 to-transparent" />
                </div>
                <CardContent className="p-6 flex-1 flex flex-col">
                    <div className="text-xl font-bold text-gray-900">
                      {t('tiles.privathaftpflicht.title', 'Privathaftpflicht')}
                    </div>
                    <div className="mt-2 text-sm text-gray-600">
                      {t(
                        'tiles.privathaftpflicht.subtitle',
                        'Schutz vor hohen Forderungen im Alltag – für ein sicheres Gefühl.'
                      )}
                    </div>

                    <div className="mt-5 text-sm text-gray-700">
                      <div className="text-xs uppercase tracking-wide text-gray-500 font-semibold">
                        {t('tiles.privathaftpflicht.exampleLabel', 'z.B. Beitragsbeispiel')}
                      </div>
                      <div className="mt-2 text-4xl font-bold text-gray-900">
                        {t('tiles.privathaftpflicht.examplePrice', '5,57€')}
                      </div>
                      <div className="mt-2 text-sm text-gray-700">
                        {t('tiles.privathaftpflicht.exampleDetails', 'pro Monat – Beispieltarif')}
                      </div>

                      <div className="mt-4 text-xs uppercase tracking-wide text-gray-500 font-semibold">
                        {t('tiles.privathaftpflicht.detailsLabel', 'Details:')}
                      </div>
                      <ul className="mt-2 space-y-1 text-sm text-gray-700">
                        <li>
                          {t(
                            'tiles.privathaftpflicht.detailsItems.0',
                            'Auslandsaufenthalt innerhalb Europas ohne zeitliche Begrenzung'
                          )}
                        </li>
                        <li>
                          {t(
                            'tiles.privathaftpflicht.detailsItems.1',
                            'nicht ehelicher Lebenspartner in häuslicher Gemeinschaft'
                          )}
                        </li>
                        <li>
                          {t(
                            'tiles.privathaftpflicht.detailsItems.2',
                            'Schadenersatz-Rechtsschutz bei Forderungsausfall'
                          )}
                        </li>
                      </ul>
                    </div>

                    <div className="flex-1" />

                    <Button asChild className="w-full mt-6 bg-red-900 hover:bg-red-950 rounded-full">
                      <Link to="/haftpflichtversicherung">
                        {t('tiles.privathaftpflicht.cta', 'Jetzt informieren')}
                        <ArrowRight className="ml-2 h-4 w-4" />
                      </Link>
                    </Button>
                  </CardContent>
                </Card>
            </div>
          </div>
        </div>
      </section>

      {/* Content */}
      <div className="min-h-screen bg-gradient-to-br from-white to-gray-50">
        <div className="container mx-auto px-4 py-16">
          <div className="max-w-6xl mx-auto">
            {/* Special Features */}
            <div className="mb-20">
              <div className="text-center mb-12">
                <h2 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">
                  {t('benefits.title', 'Ihre Vorteile als Senior')}
                </h2>
                <p className="text-lg text-gray-600 max-w-2xl mx-auto">
                  {t('benefits.subtitle', 'Wir bieten Ihnen maßgeschneiderte Lösungen für Ihre Lebensphase')}
                </p>
              </div>
              
              <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-2xl p-10 shadow-xl">
                <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
                  {benefits.map((benefit, index) => {
                    const Icon = benefitIcons[index] ?? Shield;
                    return (
                      <div key={index} className="flex items-start space-x-4 group">
                        <div className="w-12 h-12 bg-blue-600 rounded-lg flex items-center justify-center flex-shrink-0 group-hover:bg-blue-700 transition-colors">
                          <Icon className="h-6 w-6 text-white" />
                        </div>
                        <div>
                          <h3 className="font-semibold text-gray-900 mb-1">{benefit.title}</h3>
                          <p className="text-gray-600 text-sm">{benefit.desc}</p>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>

            {/* Contact Section */}
            <div className="bg-gradient-to-r from-blue-600 to-indigo-600 rounded-2xl p-10 text-center text-white shadow-2xl">
              <h2 className="text-3xl md:text-4xl font-bold mb-4">
                {t('contact.title', 'Kontaktieren Sie uns')}
              </h2>
              <p className="text-lg text-blue-100 mb-8 max-w-2xl mx-auto">
                {t('contact.subtitle', 'Lassen Sie sich unverbindlich zu Ihren Versicherungsmöglichkeiten beraten.')}
              </p>
              <div className="flex flex-col sm:flex-row gap-4 justify-center">
                <Button className="w-full sm:w-64 bg-white text-blue-600 hover:bg-gray-100 px-8 py-3 text-lg font-semibold shadow-lg">
                  <Phone className="h-5 w-5 mr-2" />
                  {t('contact.primaryCta', 'Jetzt anrufen')}
                </Button>
                <Button variant="outline" className="w-full sm:w-64 border-white text-white hover:bg-white hover:text-blue-600 px-8 py-3 text-lg font-semibold">
                  <Mail className="h-5 w-5 mr-2" />
                  {t('contact.secondaryCta', 'Termin vereinbaren')}
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <ChatbotHint />
    </Layout>
  );
};

export default Senioren;
