﻿'use client';

import { useMemo, useState } from 'react';
import { motion } from 'framer-motion';
import { config } from '@/lib/config';
import { getRuntimeClientConfig } from '@/lib/runtime-client-config';

type FolderKey = 'promo' | 'mail' | 'social';

const folderData: Record<FolderKey, Array<{ prefix: string; source: string; clicks: string }>> = {
  promo: [
    { prefix: 'sale26', source: 'example.com/spring-sale', clicks: '1 204' },
    { prefix: 'tg-ads', source: 'example.com/tg-campaign', clicks: '859' },
  ],
  mail: [
    { prefix: 'digest-04', source: 'example.com/newsletter-04', clicks: '3 410' },
    { prefix: 'welcome', source: 'example.com/onboarding', clicks: '2 150' },
  ],
  social: [
    { prefix: 'ig-bio', source: 'example.com/instagram', clicks: '5 020' },
    { prefix: 'tw-thread', source: 'example.com/twitter', clicks: '640' },
  ],
};

const SHORT_CODE_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';

function createRandomShortCode(length = 6) {
  let result = '';

  if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
    const bytes = new Uint8Array(length);
    crypto.getRandomValues(bytes);
    for (let index = 0; index < length; index += 1) {
      result += SHORT_CODE_ALPHABET[bytes[index] % SHORT_CODE_ALPHABET.length];
    }
    return result;
  }

  for (let index = 0; index < length; index += 1) {
    result += SHORT_CODE_ALPHABET[Math.floor(Math.random() * SHORT_CODE_ALPHABET.length)];
  }

  return result;
}

function normalizeInputUrl(value: string) {
  const trimmed = value.trim();
  if (!trimmed) {
    return null;
  }

  const withProtocol = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(trimmed)
    ? trimmed
    : `https://${trimmed}`;

  try {
    const parsed = new URL(withProtocol);
    if (!['http:', 'https:'].includes(parsed.protocol)) {
      return null;
    }
    return parsed.toString();
  } catch {
    return null;
  }
}

function LinkIcon({ className = 'h-5 w-5' }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
      <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
      <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
    </svg>
  );
}

export default function Hero() {
  const runtimeConfig = getRuntimeClientConfig();
  const projectName = runtimeConfig.projectName || config.projectName;
  const domain = runtimeConfig.domain || config.domain;

  const [url, setUrl] = useState('');
  const [shortened, setShortened] = useState(false);
  const [activeFolder, setActiveFolder] = useState<FolderKey>('promo');
  const [shortCode, setShortCode] = useState(() => createRandomShortCode());

  const shortUrl = useMemo(() => `${domain}/${shortCode}`, [domain, shortCode]);

  const handleShorten = (event: React.FormEvent) => {
    event.preventDefault();

    const normalizedUrl = normalizeInputUrl(url);
    if (!normalizedUrl) {
      return;
    }

    setUrl(normalizedUrl);
    setShortCode(createRandomShortCode());
    setShortened(true);
  };

  return (
    <section
      id="hero"
      className="pt-32 lg:pt-40 pb-16 px-4 sm:px-6 max-w-7xl mx-auto flex flex-col lg:flex-row items-center gap-16 relative z-10"
    >
      <div className="absolute top-[10%] left-1/2 -translate-x-1/2 w-full h-full max-w-3xl bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-violet-600/20 via-transparent to-transparent pointer-events-none blur-3xl" />

      <div className="flex-1 text-center lg:text-left z-10 w-full relative">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
          className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/[0.03] border border-white/10 text-sm text-gray-300 font-medium mb-8"
        >
          <span className="h-2 w-2 rounded-full bg-[#2AABEE]" />
          <span className="bg-gradient-to-r from-violet-300 to-blue-300 bg-clip-text text-transparent">
            Все ваши ссылки в одном месте
          </span>
        </motion.div>

        <motion.h1
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.1 }}
          className="text-5xl lg:text-6xl xl:text-7xl font-bold tracking-tight text-white leading-[1.1] mb-6"
        >
          Связывайте и
          <br className="hidden lg:block" />
          <span className="text-transparent bg-clip-text bg-gradient-to-r from-violet-400 via-fuchsia-400 to-[#2AABEE]">
            {' '}управляйте.
          </span>
        </motion.h1>

        <motion.p
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.2 }}
          className="text-lg md:text-xl text-gray-400 max-w-2xl mx-auto lg:mx-0 mb-10"
        >
          {projectName} это сокращение ссылок, папки, теги и аналитика в одной панели.
          Вход через Telegram и удобный контроль ваших кампаний.
        </motion.p>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.3 }}
          className="w-full max-w-xl mx-auto lg:mx-0 relative text-left"
        >
          {shortened ? (
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              className="bg-[#0A0A0A] border border-violet-500/50 rounded-2xl p-4 sm:p-5 shadow-[0_0_40px_rgba(139,92,246,0.3)] flex flex-col gap-4 relative z-10"
            >
              <div className="flex justify-between items-center bg-white/[0.03] rounded-xl p-3 border border-white/10">
                <div className="flex items-center gap-3 overflow-hidden">
                  <div className="w-8 h-8 rounded-full bg-violet-500/20 flex items-center justify-center shrink-0">
                    <LinkIcon className="h-4 w-4 text-violet-400" />
                  </div>
                  <div className="flex flex-col truncate pr-2">
                    <span className="text-white font-medium text-sm sm:text-base">{shortUrl}</span>
                    <span className="text-gray-500 text-xs truncate max-w-[200px]">{url}</span>
                  </div>
                </div>
                <button type="button" className="bg-white/10 hover:bg-white/20 text-white rounded-lg p-2 transition shrink-0">
                  Копия
                </button>
              </div>

              <div className="flex items-center justify-between border-t border-white/10 pt-4">
                <div className="flex items-center gap-6">
                  <div>
                    <span className="text-gray-500 text-[10px] uppercase tracking-wider block mb-1">Клики за час</span>
                    <span className="text-green-400 font-mono text-sm">24</span>
                  </div>
                  <div>
                    <span className="text-gray-500 text-[10px] uppercase tracking-wider block mb-1">Источники</span>
                    <span className="text-white font-mono text-sm">В обработке...</span>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => {
                    setShortened(false);
                    setUrl('');
                    setShortCode(createRandomShortCode());
                  }}
                  className="text-xs text-violet-400 hover:text-white transition font-medium"
                >
                  Сократить другую
                </button>
              </div>
            </motion.div>
          ) : (
            <form onSubmit={handleShorten} className="relative flex items-center group">
              <div className="absolute inset-0 rounded-2xl bg-gradient-to-r from-violet-600 to-[#2AABEE] blur-md opacity-20 group-focus-within:opacity-50 transition-opacity duration-500" />
              <div className="relative flex flex-col sm:flex-row w-full bg-[#0A0A0A] border border-white/10 rounded-2xl p-2 items-center z-10 transition-colors group-focus-within:border-violet-500/50 shadow-2xl">
                <div className="pl-4 pr-1 hidden sm:block text-gray-500">
                  <LinkIcon />
                </div>
                <input
                  type="text"
                  required
                  placeholder="Вставьте длинную ссылку..."
                  value={url}
                  onChange={(event) => setUrl(event.target.value)}
                  className="w-full bg-transparent border-none outline-none py-3 px-4 sm:px-2 text-white placeholder-gray-500 text-lg flex-1"
                  autoCapitalize="off"
                  autoCorrect="off"
                  spellCheck={false}
                />
                <button
                  type="submit"
                  className="w-full sm:w-auto bg-[#2AABEE] hover:bg-[#229ED9] text-white transition-colors px-6 py-3 rounded-xl font-medium flex items-center justify-center gap-2 whitespace-nowrap shadow-lg shadow-[#2AABEE]/20 mt-2 sm:mt-0"
                >
                  Сократить
                </button>
              </div>
            </form>
          )}
        </motion.div>
      </div>

      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ duration: 0.7, delay: 0.4 }}
        className="flex-1 w-full relative z-10"
      >
        <div className="w-full aspect-[4/3] max-w-[600px] mx-auto bg-black/40 backdrop-blur-xl border border-white/10 rounded-[2rem] overflow-hidden shadow-2xl shadow-violet-500/10 flex flex-col relative">
          <div className="absolute top-0 right-0 w-72 h-72 bg-violet-500/10 blur-3xl pointer-events-none" />

          <div className="h-14 border-b border-white/10 bg-white/5 px-4 sm:px-6 flex items-center gap-2">
            <div className="w-3 h-3 rounded-full bg-white/20" />
            <div className="w-3 h-3 rounded-full bg-white/20" />
            <div className="w-3 h-3 rounded-full bg-white/20" />
            <div className="ml-auto h-6 w-24 rounded-md bg-white/[0.03] sm:w-32" />
          </div>

          <div className="flex-1 flex text-sm relative z-10">
            <div className="w-1/3 border-r border-white/10 bg-white/[0.03] p-3 sm:p-4 flex flex-col gap-2">
              <button
                type="button"
                onClick={() => setActiveFolder('promo')}
                className={`h-9 w-full rounded font-medium flex items-center px-2 text-xs transition-colors text-left sm:px-3 sm:text-sm ${
                  activeFolder === 'promo'
                    ? 'bg-violet-500/20 text-violet-300 border border-violet-500/20'
                    : 'hover:bg-white/5 text-gray-400'
                }`}
              >
                Промо
              </button>
              <button
                type="button"
                onClick={() => setActiveFolder('mail')}
                className={`h-9 w-full rounded font-medium flex items-center px-2 text-xs transition-colors text-left sm:px-3 sm:text-sm ${
                  activeFolder === 'mail'
                    ? 'bg-fuchsia-500/20 text-fuchsia-300 border border-fuchsia-500/20'
                    : 'hover:bg-white/5 text-gray-400'
                }`}
              >
                Рассылки
              </button>
              <button
                type="button"
                onClick={() => setActiveFolder('social')}
                className={`h-9 w-full rounded font-medium flex items-center px-2 text-xs transition-colors text-left sm:px-3 sm:text-sm ${
                  activeFolder === 'social'
                    ? 'bg-blue-500/20 text-blue-300 border border-blue-500/20'
                    : 'hover:bg-white/5 text-gray-400'
                }`}
              >
                Соцсети
              </button>
            </div>

            <div className="min-w-0 flex-1 p-3 sm:p-6 flex flex-col gap-3">
              {folderData[activeFolder].map((link, index) => (
                <motion.div
                  key={`${activeFolder}-${index}`}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="p-3 sm:p-4 border border-white/10 bg-black/40 rounded-xl flex justify-between items-center gap-2 group transition hover:bg-white/5 shadow-sm"
                >
                  <div className="min-w-0 flex-1 flex flex-col gap-1">
                    <span className="text-xs sm:text-sm font-medium flex min-w-0 gap-2 items-center text-white">
                      <span className="w-2 h-2 rounded-full bg-violet-400 shadow-[0_0_8px_currentColor]" />
                      <span className="truncate">{domain}/{link.prefix}</span>
                    </span>
                    <span className="text-gray-500 text-xs truncate max-w-full ml-4">{link.source}</span>
                  </div>
                  <span className="shrink-0 text-white text-[11px] sm:text-sm font-mono bg-white/10 px-1.5 sm:px-2 py-0.5 rounded">
                    {link.clicks}
                  </span>
                </motion.div>
              ))}
            </div>
          </div>
        </div>
      </motion.div>
    </section>
  );
}

