/* global React, Icons */
const { UI: UI5 } = window;
const { Reveal: R5 } = UI5;
const { useState: useState5, useEffect: useEffect5, useRef: useRef5 } = React;

// =============================================================
// PAGE 5 — CONTACT / RDV (Conversational form)
// =============================================================

const PRESTATIONS = [
  'Vidange & Révision', 'Freins', 'Climatisation', 'Batterie', 'Pneumatiques',
  'Direction / Suspension', 'Transmission', 'Électrique', 'Dépannage',
  'Filtres', 'Alignement', 'Diagnostic moteur', 'Autre — à préciser',
];

const STEPS = [
  { id: 'firstName', q: "On commence par les bases — quel est votre prénom ?", placeholder: 'Prénom', type: 'text', required: true },
  { id: 'lastName', q: name => `Enchanté ${name}. Et votre nom de famille ?`, placeholder: 'Nom', type: 'text', required: true },
  { id: 'phone', q: "Sur quel numéro je peux vous joindre ?", placeholder: '06 12 34 56 78', type: 'tel', required: true, validate: v => /^[\d\s+().-]{8,}$/.test(v) || 'Numéro non valide' },
  { id: 'email', q: "Votre email (pour le devis écrit) ?", placeholder: 'vous@exemple.fr', type: 'email', required: true, validate: v => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) || 'Email non valide' },
  { id: 'brand', q: "Parlons voiture. Quelle marque ?", placeholder: 'Renault, Peugeot, BMW…', type: 'text', required: true },
  { id: 'model', q: brand => `Et le modèle de votre ${brand} ?`, placeholder: 'Clio, 308, Série 3…', type: 'text', required: true },
  { id: 'year', q: "Année du véhicule ?", placeholder: '2018', type: 'number', required: true, validate: v => (+v >= 1980 && +v <= 2030) || 'Année non valide' },
  { id: 'service', q: "Quel type de prestation ?", type: 'select', options: PRESTATIONS, required: true },
  { id: 'date', q: "Quelle date vous arrangerait ?", type: 'date', required: true },
  { id: 'slot', q: "Plutôt matin ou après-midi ?", type: 'choice', options: ['Matin (8h–12h)', 'Après-midi (14h–18h)'], required: true },
  { id: 'message', q: "Un message ou des précisions ? (Optionnel — vous pouvez sauter)", placeholder: "Décrivez la panne, un bruit, une demande spécifique…", type: 'textarea', required: false },
];

const ContactPage = ({ go }) => {
  const [stepIdx, setStepIdx] = useState5(0);
  const [data, setData] = useState5({});
  const [input, setInput] = useState5('');
  const [error, setError] = useState5(null);
  const [sent, setSent] = useState5(false);
  const inputRef = useRef5(null);
  const chatRef = useRef5(null);

  const step = STEPS[stepIdx];
  const done = stepIdx >= STEPS.length;

  // Focus on input when step changes
  useEffect5(() => {
    if (inputRef.current) {
      setTimeout(() => inputRef.current.focus(), 350);
    }
    // Scroll chat to bottom
    setTimeout(() => {
      if (chatRef.current) chatRef.current.scrollTop = chatRef.current.scrollHeight;
    }, 100);
  }, [stepIdx]);

  const submitValue = (val) => {
    const value = val ?? input;
    if (step.required && !value && step.type !== 'choice') {
      setError('Ce champ est requis');
      return;
    }
    if (step.validate && value) {
      const v = step.validate(value);
      if (v !== true) { setError(v); return; }
    }
    setError(null);
    setData(d => ({ ...d, [step.id]: value }));
    setInput('');
    setStepIdx(i => i + 1);
  };

  const skipMessage = () => {
    setData(d => ({ ...d, message: '' }));
    setInput('');
    setError(null);
    setStepIdx(i => i + 1);
  };

  const goBack = () => {
    if (stepIdx > 0) {
      setStepIdx(i => i - 1);
      setInput('');
      setError(null);
    }
  };

  const sendForm = () => {
    setSent(true);
  };

  const reset = () => {
    setStepIdx(0);
    setData({});
    setInput('');
    setError(null);
    setSent(false);
  };

  const getQuestion = (s, prevData) => {
    if (typeof s.q === 'function') {
      if (s.id === 'lastName') return s.q(prevData.firstName);
      if (s.id === 'model') return s.q(prevData.brand);
    }
    return s.q;
  };

  // History of completed Q&A
  const history = STEPS.slice(0, stepIdx).map((s, i) => ({
    q: getQuestion(s, data),
    a: data[s.id] || (s.required ? '—' : '(non précisé)'),
    id: s.id,
  }));

  return (
    <div className="page-enter" data-screen-label="05 Contact" style={{ paddingTop: 100, minHeight: '100vh' }}>
      <section className="section-dark" style={{ paddingTop: 32, paddingBottom: 64 }}>
        <span className="section-num">§ 05 / 05 — CONTACT / RDV</span>
        <div className="wrap">
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)',
            gap: 64,
            alignItems: 'flex-start',
          }} className="contact-grid">

            {/* LEFT — Conversational form */}
            <R5>
              <div>
                <span className="eyebrow">Demande de rendez-vous</span>
                <h1 className="h-xl" style={{ marginTop: 16, marginBottom: 16 }}>
                  On en discute<br/>en 2 minutes.
                </h1>
                <p className="body-lg" style={{ color: 'var(--gris-clair)', marginBottom: 32 }}>
                  Confirmation par SMS ou appel sous 24h.
                </p>

                {/* Chat container */}
                <div className="chat-container">
                  {/* Header */}
                  <div className="chat-header">
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                      <div className="avatar"><span className="dot-on"/>F</div>
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 14 }}>Florian — Flo'auto</div>
                        <div className="mono small" style={{ color: 'var(--gris-clair)', fontSize: 10, letterSpacing: '0.14em' }}>
                          {sent ? 'DEMANDE ENVOYÉE' : done ? 'PRÊT À ENVOYER' : `ÉTAPE ${stepIdx + 1} / ${STEPS.length}`}
                        </div>
                      </div>
                    </div>
                    <div className="mono small" style={{ color: 'var(--gris-clair)', fontSize: 10, letterSpacing: '0.14em' }}>
                      {done && !sent ? '100%' : Math.round((stepIdx / STEPS.length) * 100) + '%'}
                    </div>
                  </div>

                  {/* Progress bar */}
                  <div className="progress">
                    <div className="progress-fill" style={{ width: `${(done ? STEPS.length : stepIdx) / STEPS.length * 100}%` }} />
                  </div>

                  {/* Messages */}
                  <div className="chat-messages" ref={chatRef}>
                    <ChatMessage who="bot">
                      <p style={{ margin: 0 }}>Salut 👋 Je vous accompagne pour fixer votre rendez-vous. Quelques questions courtes, et je vous reviens sous 24h.</p>
                    </ChatMessage>

                    {history.map((h, i) => (
                      <React.Fragment key={h.id}>
                        <ChatMessage who="bot"><p style={{ margin: 0 }}>{h.q}</p></ChatMessage>
                        <ChatMessage who="user">
                          <p style={{ margin: 0 }}>{Array.isArray(h.a) ? h.a.join(', ') : h.a}</p>
                        </ChatMessage>
                      </React.Fragment>
                    ))}

                    {/* Current question */}
                    {!done && (
                      <ChatMessage who="bot" key={'q-' + stepIdx}>
                        <p style={{ margin: 0 }}>{getQuestion(step, data)}</p>
                      </ChatMessage>
                    )}

                    {/* Recap + send */}
                    {done && !sent && (
                      <React.Fragment>
                        <ChatMessage who="bot">
                          <p style={{ margin: 0, marginBottom: 16 }}>Parfait, voici le récapitulatif de votre demande :</p>
                          <div style={{
                            background: 'rgba(11,31,58,0.5)',
                            border: '1px solid var(--gris-bordure)',
                            padding: 16,
                            fontSize: 13,
                            display: 'grid',
                            gridTemplateColumns: 'auto 1fr',
                            gap: '8px 16px',
                          }} className="mono">
                            <span style={{ color: 'var(--gris-clair)' }}>NOM</span><span style={{ color: 'var(--ivoire)' }}>{data.firstName} {data.lastName}</span>
                            <span style={{ color: 'var(--gris-clair)' }}>CONTACT</span><span style={{ color: 'var(--ivoire)' }}>{data.phone} · {data.email}</span>
                            <span style={{ color: 'var(--gris-clair)' }}>VÉHICULE</span><span style={{ color: 'var(--ivoire)' }}>{data.brand} {data.model} ({data.year})</span>
                            <span style={{ color: 'var(--gris-clair)' }}>PRESTATION</span><span style={{ color: 'var(--accent)' }}>{data.service}</span>
                            <span style={{ color: 'var(--gris-clair)' }}>CRÉNEAU</span><span style={{ color: 'var(--ivoire)' }}>{data.date} · {data.slot}</span>
                            {data.message && (<>
                              <span style={{ color: 'var(--gris-clair)' }}>NOTE</span><span style={{ color: 'var(--ivoire)' }}>{data.message}</span>
                            </>)}
                          </div>
                          <p style={{ margin: '16px 0 0', fontSize: 14 }}>On envoie ?</p>
                        </ChatMessage>
                        <div style={{ display: 'flex', gap: 12, padding: '0 4px 12px', flexWrap: 'wrap' }}>
                          <button className="btn btn-primary" onClick={sendForm}>
                            <Icons.Send width="14" height="14"/> Envoyer la demande
                          </button>
                          <button className="btn btn-secondary" style={{ color: 'var(--ivoire)' }} onClick={goBack}>
                            Modifier
                          </button>
                        </div>
                      </React.Fragment>
                    )}

                    {sent && (
                      <ChatMessage who="bot">
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'flex-start' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                            <Icons.Check width="20" height="20" style={{ color: '#4ade80' }}/>
                            <strong style={{ color: 'var(--ivoire)', fontSize: 16 }}>Demande envoyée !</strong>
                          </div>
                          <p style={{ margin: 0, fontSize: 14 }}>
                            Merci {data.firstName}. Je vous reviens par SMS ou appel sous 24h pour confirmer le créneau du {data.date}.
                          </p>
                          <div style={{ display: 'flex', gap: 12, marginTop: 8, flexWrap: 'wrap' }}>
                            <button className="btn btn-secondary" style={{ color: 'var(--ivoire)', fontSize: 11 }} onClick={() => go('accueil')}>
                              Retour à l'accueil
                            </button>
                            <button className="btn btn-ghost" style={{ color: 'var(--gris-clair)', fontSize: 11 }} onClick={reset}>
                              Nouvelle demande
                            </button>
                          </div>
                        </div>
                      </ChatMessage>
                    )}
                  </div>

                  {/* Input area */}
                  {!done && (
                    <div className="chat-input">
                      <StepInput
                        step={step}
                        value={input}
                        setValue={setInput}
                        error={error}
                        onSubmit={submitValue}
                        inputRef={inputRef}
                        onSkip={step.required ? null : skipMessage}
                        onBack={stepIdx > 0 ? goBack : null}
                      />
                    </div>
                  )}
                </div>
              </div>
            </R5>

            {/* RIGHT — Sidebar contact infos */}
            <R5 delay={120}>
              <aside style={{ position: 'sticky', top: 120, display: 'flex', flexDirection: 'column', gap: 24 }}>
                <div className="info-card">
                  <span className="eyebrow">Coordonnées</span>
                  <div className="info-item">
                    <Icons.Phone width="18" height="18" style={{ color: 'var(--accent)', flexShrink: 0 }} />
                    <a href="tel:+33000000000" style={{ color: 'var(--ivoire)' }}>06 12 34 56 78</a>
                  </div>
                  <div className="info-item">
                    <Icons.Mail width="18" height="18" style={{ color: 'var(--accent)', flexShrink: 0 }} />
                    <a href="mailto:contact@floauto.fr" style={{ color: 'var(--ivoire)' }}>contact@floauto.fr</a>
                  </div>
                  <div className="info-item">
                    <Icons.MapPin width="18" height="18" style={{ color: 'var(--accent)', flexShrink: 0, marginTop: 2 }} />
                    <span>14 rue de l'Atelier<br/>27730 Bueil</span>
                  </div>
                </div>

                <div className="info-card">
                  <span className="eyebrow">Horaires</span>
                  <div className="hours-row"><span>Lun — Ven</span><span className="mono">8h — 18h</span></div>
                  <div className="hours-row"><span>Samedi</span><span className="mono">9h — 12h</span></div>
                  <div className="hours-row" style={{ color: 'var(--gris-clair)' }}><span>Dimanche</span><span className="mono">Fermé</span></div>
                  <div style={{ marginTop: 16, padding: 12, border: '1px solid var(--accent)', display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span className="pulse-dot" />
                    <span className="mono small" style={{ color: 'var(--accent)', letterSpacing: '0.14em', textTransform: 'uppercase', fontSize: 11 }}>Uniquement sur RDV</span>
                  </div>
                </div>

                {/* Map placeholder */}
                <div style={{ position: 'relative' }}>
                  <UI5.ImgPlaceholder tag="GOOGLE MAPS" label="Carte interactive" icon={Icons.MapPin} style={{ aspectRatio: '1', width: '100%' }} />
                </div>
              </aside>
            </R5>
          </div>
        </div>
      </section>

      <style>{`
        .chat-container {
          background: var(--bleu-moyen);
          border: 1px solid var(--gris-bordure);
          display: flex;
          flex-direction: column;
          min-height: 600px;
          max-height: 720px;
          overflow: hidden;
        }
        .chat-header {
          padding: 16px 20px;
          border-bottom: 1px solid var(--gris-bordure);
          display: flex;
          justify-content: space-between;
          align-items: center;
          background: rgba(11,31,58,0.4);
        }
        .avatar {
          width: 40px; height: 40px;
          background: var(--accent);
          color: var(--blanc);
          display: flex; align-items: center; justify-content: center;
          font-family: var(--font-display);
          font-weight: 800;
          font-size: 18px;
          position: relative;
        }
        .dot-on {
          position: absolute;
          right: -2px; bottom: -2px;
          width: 10px; height: 10px;
          border-radius: 50%;
          background: #4ade80;
          border: 2px solid var(--bleu-moyen);
        }
        .progress {
          height: 2px;
          background: var(--gris-bordure);
          overflow: hidden;
        }
        .progress-fill {
          height: 100%;
          background: var(--accent);
          transition: width 0.5s cubic-bezier(.2,.7,.2,1);
        }
        .chat-messages {
          flex: 1;
          padding: 20px;
          overflow-y: auto;
          display: flex;
          flex-direction: column;
          gap: 12px;
          scroll-behavior: smooth;
        }
        .chat-messages::-webkit-scrollbar { width: 6px; }
        .chat-messages::-webkit-scrollbar-track { background: transparent; }
        .chat-messages::-webkit-scrollbar-thumb { background: var(--gris-bordure); border-radius: 3px; }

        .msg {
          max-width: 85%;
          padding: 12px 16px;
          font-size: 14px;
          line-height: 1.5;
          animation: msgIn 0.35s cubic-bezier(.2,.7,.2,1);
        }
        .msg.bot {
          background: var(--nuit);
          border: 1px solid var(--gris-bordure);
          align-self: flex-start;
          border-bottom-left-radius: 0;
        }
        .msg.user {
          background: var(--accent);
          color: var(--blanc);
          align-self: flex-end;
          border-bottom-right-radius: 0;
        }
        @keyframes msgIn {
          from { opacity: 0; transform: translateY(8px); }
          to { opacity: 1; transform: none; }
        }

        .chat-input {
          padding: 16px;
          border-top: 1px solid var(--gris-bordure);
          background: rgba(11,31,58,0.4);
        }
        .chat-input-row {
          display: flex;
          gap: 8px;
          align-items: stretch;
        }
        .chat-text-input {
          flex: 1;
          padding: 14px 16px;
          background: var(--nuit);
          border: 1px solid var(--gris-bordure);
          color: var(--ivoire);
          font-family: var(--font-display);
          font-size: 15px;
          outline: none;
          transition: border-color 0.2s;
        }
        .chat-text-input:focus { border-color: var(--accent); }
        .chat-text-input.error { border-color: #ef4444; }
        textarea.chat-text-input { min-height: 80px; resize: vertical; font-family: inherit; }

        .send-btn {
          padding: 0 18px;
          background: var(--accent);
          color: var(--blanc);
          display: flex; align-items: center; justify-content: center;
          transition: background 0.15s;
        }
        .send-btn:hover { background: #1860c0; }
        .send-btn:disabled { background: var(--gris-bordure); cursor: not-allowed; }

        .err-msg {
          margin-top: 8px;
          font-size: 12px;
          color: #ef4444;
          font-family: var(--font-mono);
          letter-spacing: 0.06em;
        }

        .choice-grid {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 8px;
          margin-bottom: 8px;
        }
        .choice-grid.cols-3 { grid-template-columns: repeat(2, 1fr); }
        .choice-btn {
          padding: 14px;
          background: var(--nuit);
          border: 1px solid var(--gris-bordure);
          color: var(--ivoire);
          font-size: 14px;
          text-align: left;
          transition: all 0.15s;
          font-family: inherit;
        }
        .choice-btn:hover {
          border-color: var(--accent);
          background: rgba(30,111,217,0.1);
        }

        .select-list {
          max-height: 240px;
          overflow-y: auto;
          border: 1px solid var(--gris-bordure);
          margin-bottom: 8px;
        }
        .select-list::-webkit-scrollbar { width: 6px; }
        .select-list::-webkit-scrollbar-thumb { background: var(--gris-bordure); }
        .select-option {
          width: 100%;
          padding: 12px 16px;
          background: transparent;
          border: 0;
          border-bottom: 1px solid var(--gris-bordure);
          color: var(--ivoire);
          font-size: 14px;
          text-align: left;
          cursor: pointer;
          transition: background 0.1s;
          font-family: inherit;
        }
        .select-option:hover { background: rgba(30,111,217,0.15); color: var(--accent); }
        .select-option:last-child { border-bottom: 0; }

        .input-helper {
          display: flex;
          justify-content: space-between;
          margin-top: 10px;
          font-family: var(--font-mono);
          font-size: 10px;
          letter-spacing: 0.14em;
          text-transform: uppercase;
          color: var(--gris-clair);
        }
        .input-helper a, .input-helper button {
          color: var(--gris-clair);
          cursor: pointer;
          background: none; border: 0; padding: 0; font: inherit;
        }
        .input-helper a:hover, .input-helper button:hover { color: var(--accent); }

        /* Sidebar info cards */
        .info-card {
          background: var(--bleu-moyen);
          border: 1px solid var(--gris-bordure);
          padding: 24px;
          display: flex;
          flex-direction: column;
          gap: 14px;
        }
        .info-card .eyebrow { margin-bottom: 4px; }
        .info-item {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          font-size: 14px;
          line-height: 1.5;
        }
        .info-item a { color: var(--ivoire); transition: color 0.2s; }
        .info-item a:hover { color: var(--accent); }
        .hours-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 14px;
          padding: 6px 0;
          border-bottom: 1px solid var(--gris-bordure);
        }
        .hours-row:last-of-type { border-bottom: 0; }
        .pulse-dot {
          width: 8px; height: 8px; border-radius: 50%;
          background: #4ade80;
          box-shadow: 0 0 0 0 #4ade80;
          animation: pulseDot 1.8s ease-out infinite;
        }
        @keyframes pulseDot {
          0%, 100% { box-shadow: 0 0 0 0 rgba(74,222,128, 0.7); }
          50% { box-shadow: 0 0 0 6px rgba(74,222,128, 0); }
        }

        @media (max-width: 880px) {
          .contact-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </div>
  );
};

// ---- ChatMessage ----
const ChatMessage = ({ who, children }) => (
  <div className={`msg ${who}`}>{children}</div>
);

// ---- StepInput ----
const StepInput = ({ step, value, setValue, error, onSubmit, inputRef, onSkip, onBack }) => {
  const onKey = (e) => {
    if (e.key === 'Enter' && step.type !== 'textarea') {
      e.preventDefault();
      onSubmit();
    }
    if (e.key === 'Enter' && (e.metaKey || e.ctrlKey) && step.type === 'textarea') {
      e.preventDefault();
      onSubmit();
    }
  };

  if (step.type === 'select') {
    return (
      <div>
        <div className="select-list">
          {step.options.map(o => (
            <button key={o} className="select-option" onClick={() => onSubmit(o)}>{o}</button>
          ))}
        </div>
        <div className="input-helper">
          {onBack ? <button onClick={onBack}>← Précédent</button> : <span/>}
          <span>↵ POUR VALIDER</span>
        </div>
      </div>
    );
  }
  if (step.type === 'choice') {
    return (
      <div>
        <div className="choice-grid">
          {step.options.map(o => (
            <button key={o} className="choice-btn" onClick={() => onSubmit(o)}>{o}</button>
          ))}
        </div>
        <div className="input-helper">
          {onBack ? <button onClick={onBack}>← Précédent</button> : <span/>}
          <span>CLIQUEZ POUR CHOISIR</span>
        </div>
      </div>
    );
  }
  if (step.type === 'textarea') {
    return (
      <div>
        <div className="chat-input-row">
          <textarea
            ref={inputRef}
            className={`chat-text-input ${error ? 'error' : ''}`}
            placeholder={step.placeholder}
            value={value}
            onChange={e => setValue(e.target.value)}
            onKeyDown={onKey}
            rows={3}
          />
          <button className="send-btn" onClick={() => onSubmit()}>
            <Icons.Send width="18" height="18" />
          </button>
        </div>
        {error && <div className="err-msg">{error}</div>}
        <div className="input-helper">
          {onBack ? <button onClick={onBack}>← Précédent</button> : <span/>}
          <div style={{ display: 'flex', gap: 16 }}>
            {onSkip && <button onClick={onSkip}>Sauter →</button>}
            <span>⌘ + ↵ POUR ENVOYER</span>
          </div>
        </div>
      </div>
    );
  }
  // text / tel / email / number / date
  return (
    <div>
      <div className="chat-input-row">
        <input
          ref={inputRef}
          type={step.type}
          className={`chat-text-input ${error ? 'error' : ''}`}
          placeholder={step.placeholder || ''}
          value={value}
          onChange={e => setValue(e.target.value)}
          onKeyDown={onKey}
          min={step.type === 'number' ? 1980 : undefined}
          max={step.type === 'number' ? 2030 : undefined}
        />
        <button className="send-btn" onClick={() => onSubmit()} disabled={step.required && !value}>
          <Icons.ArrowRight width="18" height="18" />
        </button>
      </div>
      {error && <div className="err-msg">{error}</div>}
      <div className="input-helper">
        {onBack ? <button onClick={onBack}>← Précédent</button> : <span/>}
        <span>↵ POUR VALIDER</span>
      </div>
    </div>
  );
};

window.ContactPage = ContactPage;
