const { useState, useEffect, useRef, useCallback, createContext, useContext } = React;

// ──────────────────────────────────────────────────────────────
// ElevenLabs config
// ──────────────────────────────────────────────────────────────
// 1) Agente PÚBLICO (allowlist desactivada en el dashboard):
//      basta con pegar el agentId aquí.
// 2) Agente PRIVADO:
//      tu backend debe devolver un signed URL desde la API de ElevenLabs
//      (GET /v1/convai/conversation/get-signed-url?agent_id=...).
//      Deja AGENT_ID en "" y pon la URL de tu endpoint en SIGNED_URL_ENDPOINT.
const ELEVENLABS = {
  AGENT_ID: 'agent_5901kskjrvbhfd284dy26c6606fg',          // <-- pega aquí tu agentId
  SIGNED_URL_ENDPOINT: '',                  // <-- o pon aquí tu endpoint (ej. '/api/elevenlabs/signed-url')
};

// --- i18n ---
const COPY = {
  es: {
    nav_services: 'Servicios',
    eyebrow: 'Voice Agent · En línea',
    headline_a: 'Una voz que',
    headline_em: 'escucha',
    headline_b: ', responde y agenda por ti.',
    subheadline: 'Agentes de voz AI para tu negocio. Atienden, prospectan, agendan y dan seguimiento — todo el día, en español natural.',
    cta: 'Agenda una demo con voz',
    cta_alert: 'Demo solicitada ✦',
    powered: 'Powered by ElevenLabs',
    capacities: 'Capacidades',
    state_idle: 'Toca para hablar con tu agente',
    state_listening: 'Escuchando…',
    state_processing: 'Procesando…',
    speech: 'Hola, soy tu asistente de voz. ¿En qué puedo ayudarte hoy?',
    aria_activate: 'Activar agente de voz',
    aria_stop: 'Detener agente de voz',
    aria_services: 'Capacidades del voicebot',
    aria_lang: 'Cambiar idioma',
    footer: '© 2026 Arkana Tech',
    services: [
      { title: 'Llamadas Entrantes', desc: '24/7, sin tiempos de espera' },
      { title: 'Llamadas Salientes', desc: 'Leads, seguimiento y reactivación' },
      { title: 'Agendar Citas', desc: 'Integración directa con tu calendario' },
      { title: 'Calificación de Leads', desc: 'Califica y enriquece en tiempo real' },
      { title: 'Fuera de Horario', desc: 'Nunca pierdas una llamada' },
      { title: 'Soporte Multilingüe', desc: 'Inglés y español nativos' },
      { title: 'Auto-Logging al CRM', desc: 'Resumen y notas después de cada llamada' },
      { title: 'Transferencia a Humano', desc: 'Escalado inteligente cuando el caso lo requiere' },
    ],
  },
  en: {
    nav_services: 'Services',
    eyebrow: 'Voice Agent · Online',
    headline_a: 'A voice that',
    headline_em: 'listens',
    headline_b: ', answers, and books for you.',
    subheadline: 'AI voice agents for your business. They answer, prospect, schedule and follow up — all day, in natural language.',
    cta: 'Book a demo by voice',
    cta_alert: 'Demo requested ✦',
    powered: 'Powered by ElevenLabs',
    capacities: 'Capabilities',
    state_idle: 'Tap to talk with your agent',
    state_listening: 'Listening…',
    state_processing: 'Processing…',
    speech: "Hi, I'm your voice assistant. How can I help you today?",
    aria_activate: 'Activate voice agent',
    aria_stop: 'Stop voice agent',
    aria_services: 'Voicebot capabilities',
    aria_lang: 'Change language',
    footer: '© 2026 Arkana Tech',
    services: [
      { title: 'Inbound Calls', desc: '24/7, zero wait time' },
      { title: 'Outbound Calls', desc: 'Leads, follow-ups and reactivation' },
      { title: 'Book Appointments', desc: 'Direct calendar integration' },
      { title: 'Lead Qualification', desc: 'Qualify and enrich in real time' },
      { title: 'After-Hours Coverage', desc: 'Never miss a call' },
      { title: 'Multilingual Support', desc: 'Native English and Spanish' },
      { title: 'CRM Auto-Logging', desc: 'Summary and notes after every call' },
      { title: 'Human Handoff', desc: 'Smart escalation when the case demands it' },
    ],
  },
};

const LangContext = createContext({ lang: 'es', setLang: () => {}, t: COPY.es });
const useT = () => useContext(LangContext);

// --- Icons ---
const Icon = {
  PhoneOut: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z" />
      <path d="M16 4l4-4M20 4h-4M20 4v4" />
    </svg>
  ),
  PhoneIn: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z" />
      <path d="M16 4l4 4M20 4l-4 4" />
    </svg>
  ),
  Calendar: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4" width="18" height="18" rx="2" />
      <path d="M16 2v4M8 2v4M3 10h18" />
      <circle cx="12" cy="15" r="1.2" fill="currentColor" />
    </svg>
  ),
  Target: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9" />
      <circle cx="12" cy="12" r="5" />
      <circle cx="12" cy="12" r="1.5" fill="currentColor" />
    </svg>
  ),
  Mail: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="5" width="18" height="14" rx="2" />
      <path d="M3 7l9 7 9-7" />
    </svg>
  ),
  Brain: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 4a3 3 0 0 0-3 3v.5A2.5 2.5 0 0 0 6.5 10 2.5 2.5 0 0 0 4 12.5 2.5 2.5 0 0 0 6.5 15a3 3 0 0 0 3 3 3 3 0 0 0 2.5-1.3" />
      <path d="M12 4a3 3 0 0 1 3 3v.5A2.5 2.5 0 0 1 17.5 10 2.5 2.5 0 0 1 20 12.5a2.5 2.5 0 0 1-2.5 2.5 3 3 0 0 1-3 3 3 3 0 0 1-2.5-1.3" />
      <path d="M12 4v14" />
    </svg>
  ),
  Moon: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z" />
    </svg>
  ),
  Globe: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="9" />
      <path d="M3 12h18" />
      <path d="M12 3a14 14 0 0 1 0 18" />
      <path d="M12 3a14 14 0 0 0 0 18" />
    </svg>
  ),
  Clipboard: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
      <rect x="5" y="4" width="14" height="17" rx="2" />
      <rect x="9" y="2" width="6" height="4" rx="1" />
      <path d="M9 11h6M9 15h6M9 19h3" />
    </svg>
  ),
  Handoff: () => (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="7" cy="7" r="3" />
      <circle cx="17" cy="17" r="3" />
      <path d="M14 7h5M19 7l-2-2M19 7l-2 2" />
      <path d="M10 17H5M5 17l2-2M5 17l2 2" />
    </svg>
  ),
  ArrowRight: () => (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  ),
};

const SERVICE_ICONS = [Icon.PhoneIn, Icon.PhoneOut, Icon.Calendar, Icon.Target, Icon.Moon, Icon.Globe, Icon.Clipboard, Icon.Handoff];

// --- Logo ---
function Logo() {
  return (
    <a
      href="https://arkanatech.tech"
      target="_blank"
      rel="noopener noreferrer"
      className="logo"
      aria-label="Arkana Tech"
    >
      <img src="./assets/arkana-mark.png" alt="" className="logo-mark-img" />
      <span className="logo-wordmark">
        <span className="lw-arkana">Arkana</span>
        <span className="lw-tech">Tech</span>
      </span>
    </a>
  );
}

// --- Language toggle ---
function LangToggle() {
  const { lang, setLang, t } = useT();
  return (
    <div
      className="lang-toggle"
      role="group"
      aria-label={t.aria_lang}
    >
      <button
        className={`lang-opt ${lang === 'es' ? 'is-active' : ''}`}
        onClick={() => setLang('es')}
        aria-pressed={lang === 'es'}
      >
        ES
      </button>
      <span className="lang-divider" aria-hidden="true"></span>
      <button
        className={`lang-opt ${lang === 'en' ? 'is-active' : ''}`}
        onClick={() => setLang('en')}
        aria-pressed={lang === 'en'}
      >
        EN
      </button>
      <span
        className="lang-pill"
        aria-hidden="true"
        style={{ transform: `translateX(${lang === 'es' ? '0%' : '100%'})` }}
      ></span>
    </div>
  );
}

// --- Header ---
function Header() {
  const { t } = useT();
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <header className={`header ${scrolled ? 'scrolled' : ''}`}>
      <Logo />
      <div className="header-right">
        <nav>
          <a className="nav-link" href="https://arkanatech.tech/" target="_blank" rel="noopener noreferrer">{t.nav_services}</a>
        </nav>
        <LangToggle />
      </div>
    </header>
  );
}

// --- Core ---
function VoiceCore({ state, onClick, speechText, onEnd }) {
  const { t, lang } = useT();
  const isActive = state !== 'idle';
  return (
    <div className={`core-wrap ${state}`}>
      <div className="core-rings" aria-hidden="true">
        <div className="ring ring-1"></div>
        <div className="ring ring-2"></div>
        <div className="ring ring-3"></div>
        <div className="ring ring-4"></div>
        <div className="ring ring-5"></div>
      </div>

      <button
        className="core-btn"
        onClick={onClick}
        aria-label={state === 'idle' ? t.aria_activate : t.aria_stop}
      >
        <div className="eq">
          <span></span><span></span><span></span><span></span><span></span>
        </div>
      </button>

      <StateCaption state={state} speechText={speechText} />

      {isActive && (
        <button
          className="end-call-btn"
          onClick={(e) => { e.stopPropagation(); onEnd && onEnd(); }}
          aria-label={lang === 'es' ? 'Finalizar llamada' : 'End call'}
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M10.7 13.3a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.7 2v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1" transform="rotate(135 12 12)"/>
          </svg>
          <span>{lang === 'es' ? 'Finalizar llamada' : 'End call'}</span>
        </button>
      )}
    </div>
  );
}

function StateCaption({ state, speechText }) {
  const { t } = useT();
  if (state === 'idle') return <div className="state-caption">{t.state_idle}</div>;
  if (state === 'listening') return <div className="state-caption">{t.state_listening}</div>;
  if (state === 'processing') return <div className="state-caption">{t.state_processing}</div>;
  // 'speaking' is rendered inside ChatWindow on the side panel
  return <div className="state-caption speaking-status">{t.state_speaking || 'Hablando…'}</div>;
}

// --- Chat window (left side, typewriter) ---
function ChatWindow({ state, speechText }) {
  const { lang } = useT();
  const [displayed, setDisplayed] = useState('');
  const target = speechText || '';

  // Reset when a brand-new utterance starts (target no longer starts with displayed)
  useEffect(() => {
    if (!target) { setDisplayed(''); return; }
    if (!target.startsWith(displayed)) setDisplayed('');
  }, [target]);

  // Type one char at a time toward the target
  useEffect(() => {
    if (!target || displayed.length >= target.length) return;
    const id = setTimeout(() => {
      setDisplayed(target.slice(0, displayed.length + 1));
    }, 22);
    return () => clearTimeout(id);
  }, [target, displayed]);

  if (state === 'idle' && !displayed) return null;

  const isTyping = displayed.length < target.length;
  const statusLabel = (() => {
    if (state === 'listening') return lang === 'es' ? 'Escuchando' : 'Listening';
    if (state === 'processing') return lang === 'es' ? 'Pensando' : 'Thinking';
    if (state === 'speaking') return lang === 'es' ? 'Hablando' : 'Speaking';
    return lang === 'es' ? 'Conectado' : 'Connected';
  })();

  const placeholder = (() => {
    if (state === 'listening') return lang === 'es' ? 'Te escucho…' : "I'm listening…";
    if (state === 'processing') return lang === 'es' ? 'Procesando tu mensaje…' : 'Processing your message…';
    return '';
  })();

  return (
    <aside className={`chat-window ${state}`} aria-live="polite">
      <header className="chat-window__header">
        <div className="chat-window__avatar" aria-hidden="true">
          <span></span><span></span><span></span>
        </div>
        <div className="chat-window__title">
          <strong>{lang === 'es' ? 'Asistente de voz' : 'Voice assistant'}</strong>
          <span className="chat-window__status">
            <span className="chat-window__dot"></span>
            {statusLabel}
          </span>
        </div>
      </header>
      <div className="chat-window__body">
        {displayed ? (
          <div className="chat-bubble">
            {displayed}
            {(isTyping || state === 'speaking') && <span className="chat-caret"></span>}
          </div>
        ) : (
          <div className="chat-window__placeholder">
            <span className="chat-window__dots"><span></span><span></span><span></span></span>
            {placeholder}
          </div>
        )}
      </div>
    </aside>
  );
}

// --- Services panel ---
function ServicesPanel({ onServiceClick }) {
  const { lang, t } = useT();
  return (
    <aside
      key={lang}
      className="services-panel"
      id="servicios"
      aria-label={t.aria_services}
    >
      <div className="services-header">
        <h3>{t.capacities}</h3>
        <span className="count">08 / 08</span>
      </div>
      <ul className="services-list">
        {t.services.map((s, i) => {
          const IconCmp = SERVICE_ICONS[i];
          return (
            <li
              key={s.title}
              className="service-item is-interactive"
              role="button"
              tabIndex={0}
              onClick={() => onServiceClick && onServiceClick(s, i)}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  onServiceClick && onServiceClick(s, i);
                }
              }}
              aria-label={`${s.title} — ${t.ask_example_aria || 'preguntar por un ejemplo'}`}
            >
              <div className="service-icon"><IconCmp /></div>
              <div className="service-text">
                <div className="service-title">{s.title}</div>
                <div className="service-desc">{s.desc}</div>
              </div>
              <div className="service-cta" aria-hidden="true">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
              </div>
            </li>
          );
        })}
      </ul>
    </aside>
  );
}

// --- App body that consumes lang context ---
function Page() {
  const { lang, t } = useT();
  const [state, setState] = useState('idle');
  const [speechText, setSpeechText] = useState('');
  const timersRef = useRef([]);
  const conversationRef = useRef(null);

  const clearTimers = () => {
    timersRef.current.forEach(clearTimeout);
    timersRef.current = [];
  };

  // when language flips mid-speech, reset to idle and close any live call
  useEffect(() => {
    clearTimers();
    if (conversationRef.current) {
      conversationRef.current.endSession().catch(() => {});
      conversationRef.current = null;
    }
    setState('idle');
    setSpeechText('');
  }, [lang]);

  // ── ElevenLabs session ────────────────────────────────────────
  const waitForSDK = () => new Promise((resolve) => {
    if (window.ElevenLabsConversation) return resolve(window.ElevenLabsConversation);
    window.addEventListener('elevenlabs-ready', () => resolve(window.ElevenLabsConversation), { once: true });
  });

  const startCall = useCallback(async (opts = {}) => {
    clearTimers();
    setState('processing'); // conectando…
    setSpeechText('');

    // Una vez que el agente termina su primera intervención (greeting), inyectamos
    // el "user message" del servicio. Esto evita el conflicto de turnos que cerraba
    // la sesión cuando intentábamos mandar firstMessage + userMessage simultáneos.
    let firstReplyDone = false;
    let prevMode = null;

    try {
      // Permiso de micro
      await navigator.mediaDevices.getUserMedia({ audio: true });

      const Conversation = await waitForSDK();
      if (!Conversation) throw new Error('ElevenLabs SDK no cargado');

      const sessionOpts = {
        onConnect: () => setState('listening'),
        onDisconnect: () => {
          setState('idle');
          setSpeechText('');
          conversationRef.current = null;
        },
        onError: (err) => {
          console.error('[ElevenLabs] error', err);
          setState('idle');
          setSpeechText('');
          conversationRef.current = null;
        },
        onModeChange: ({ mode }) => {
          setState(mode);
          if (mode === 'listening') setSpeechText('');

          // Cuando el agente pasa de "speaking" → "listening" por primera vez,
          // su saludo inicial ya terminó. Es seguro inyectar el mensaje del
          // usuario sobre el servicio.
          if (
            prevMode === 'speaking' &&
            mode === 'listening' &&
            !firstReplyDone &&
            opts.userMessage &&
            conversationRef.current
          ) {
            firstReplyDone = true;
            try { conversationRef.current.sendUserMessage?.(opts.userMessage); } catch (_) {}
          }
          prevMode = mode;
        },
        onMessage: ({ source, message }) => {
          if (source === 'ai' && message) setSpeechText(message);
        },
      };

      if (ELEVENLABS.SIGNED_URL_ENDPOINT) {
        const r = await fetch(ELEVENLABS.SIGNED_URL_ENDPOINT);
        const { signed_url, signedUrl } = await r.json();
        sessionOpts.signedUrl = signed_url || signedUrl;
      } else {
        sessionOpts.agentId = ELEVENLABS.AGENT_ID;
      }

      // Solo overrideamos el IDIOMA (que es el override más estable).
      // El firstMessage lo dejamos al agente para no romper la negociación
      // inicial. La selección del servicio se inyecta DESPUÉS del saludo
      // usando sendUserMessage al detectar fin del primer turno del agente.
      sessionOpts.overrides = { agent: { language: lang } };

      let conversation;
      try {
        conversation = await Conversation.startSession(sessionOpts);
      } catch (overrideErr) {
        console.warn('[ElevenLabs] overrides rechazados, reintentando sin overrides:', overrideErr);
        delete sessionOpts.overrides;
        conversation = await Conversation.startSession(sessionOpts);
      }
      conversationRef.current = conversation;

      // Refuerzo de idioma vía contextual update — con delay para no chocar
      // con el saludo del agente. No requiere config en dashboard.
      setTimeout(() => {
        if (!conversationRef.current) return;
        const langDirective = lang === 'es'
          ? 'IMPORTANTE: El usuario seleccionó español. Responde SIEMPRE en español de aquí en adelante.'
          : 'IMPORTANT: The user selected English. From now on, reply ONLY in English.';
        try { conversationRef.current.sendContextualUpdate?.(langDirective); } catch (_) {}
        if (opts.contextualUpdate) {
          try { conversationRef.current.sendContextualUpdate?.(opts.contextualUpdate); } catch (_) {}
        }
      }, 400);
    } catch (err) {
      console.error('[ElevenLabs] startCall failed', err);
      setState('idle');
      setSpeechText(
        lang === 'es'
          ? 'No pude iniciar la llamada. Revisa el micrófono.'
          : "Couldn't start the call. Please check your mic."
      );
      setTimeout(() => setSpeechText(''), 3500);
    }
  }, [lang]);

  const endCall = useCallback(async () => {
    clearTimers();
    try {
      if (conversationRef.current) await conversationRef.current.endSession();
    } catch (e) { /* ignore */ }
    conversationRef.current = null;
    setState('idle');
    setSpeechText('');
  }, []);

  const handleCoreClick = () => {
    if (state === 'idle') startCall();
    else endCall();
  };

  // Clic en una capacidad → que el agente reconozca el servicio y ofrezca ejemplo
  const askAboutService = useCallback((service) => {
    const userMessage = lang === 'es'
      ? `Me interesa ${service.title}. ¿Me puedes dar un ejemplo de cómo funciona?`
      : `I'm interested in ${service.title}. Could you walk me through an example of how it works?`;
    const contextualUpdate = lang === 'es'
      ? `El usuario hizo clic en la capacidad "${service.title}" (${service.desc}). Responde en español y ofrece un ejemplo concreto.`
      : `User clicked the capability "${service.title}" (${service.desc}). Reply in English only and offer a concrete example.`;

    // Si ya hay llamada activa, manda el mensaje del usuario directamente
    if (conversationRef.current) {
      try { conversationRef.current.sendContextualUpdate?.(contextualUpdate); } catch (_) {}
      try { conversationRef.current.sendUserMessage?.(userMessage); } catch (_) {}
      return;
    }
    // Si no, arranca la sesión. El userMessage se inyectará automáticamente
    // cuando el agente termine su saludo inicial (detectado por onModeChange).
    startCall({ userMessage, contextualUpdate });
  }, [lang, startCall]);

  useEffect(() => () => {
    clearTimers();
    if (conversationRef.current) {
      conversationRef.current.endSession().catch(() => {});
      conversationRef.current = null;
    }
  }, []);

  return (
    <React.Fragment>
      <Header />
      <ChatWindow state={state} speechText={speechText} />
      <main className="stage">
        <div className="eyebrow" key={`eb-${lang}`}>
          <span className="dot"></span>
          <span>{t.eyebrow}</span>
        </div>

        <h1 className="headline" key={`h-${lang}`}>
          {t.headline_a} <em>{t.headline_em}</em>{t.headline_b}
        </h1>
        <p className="subheadline" key={`s-${lang}`}>{t.subheadline}</p>

        <VoiceCore state={state} onClick={handleCoreClick} speechText={speechText} onEnd={endCall} />

        <div className="cta-zone">
          <a
            className="cta-btn"
            href="https://arkanatech.tech/contacto/"
            target="_blank"
            rel="noopener noreferrer"
          >
            {t.cta}
            <Icon.ArrowRight />
          </a>
        </div>

        <ServicesPanel onServiceClick={askAboutService} />
      </main>

      <footer className="footer">
        <p>
          © 2026{' '}
          <a
            href="https://arkanatech.tech/"
            target="_blank"
            rel="noopener noreferrer"
            className="footer-link"
          >
            Arkana Tech
          </a>
        </p>
      </footer>
    </React.Fragment>
  );
}

// --- App with language provider ---
function App() {
  const [lang, setLang] = useState(() => {
    const stored = localStorage.getItem('arkana_lang');
    if (stored === 'es' || stored === 'en') return stored;
    return (navigator.language || '').toLowerCase().startsWith('en') ? 'en' : 'es';
  });

  useEffect(() => {
    localStorage.setItem('arkana_lang', lang);
    document.documentElement.lang = lang;
  }, [lang]);

  return (
    <LangContext.Provider value={{ lang, setLang, t: COPY[lang] }}>
      <Page />
    </LangContext.Provider>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
