/* global React */
const { useState, useEffect } = React;

function DeployModal({ state, onClose, onLive }) {
  const { t, lang } = useT();
  const [phase, setPhase] = useState(0); // 0..3 done
  const [copied, setCopied] = useState(false);
  const url = `https://${slug(state.title) || "untitled"}.aimaker.app`;

  useEffect(() => {
    const timers = [
      setTimeout(() => setPhase(1), 900),
      setTimeout(() => setPhase(2), 1900),
      setTimeout(() => setPhase(3), 2900),
    ];
    return () => timers.forEach(clearTimeout);
  }, []);

  const phases = [
    { label: t.dep_building, done: phase >= 1 },
    { label: t.dep_uploading, done: phase >= 2 },
    { label: t.dep_warming, done: phase >= 3 },
  ];

  const isDone = phase === 3;

  return (
    <div className="modal-backdrop">
      <div className="modal">
        <div className="modal-head">
          <span className="modal-eyebrow">aimaker · deploy</span>
          <button className="modal-close" onClick={onClose}><Icon.close /></button>
        </div>

        {!isDone ? (
          <>
            <h3 className="modal-title">{t.dep_title}</h3>
            <ul className="phase-list">
              {phases.map((p, i) => (
                <li key={i} className={`phase ${p.done ? "is-done" : (i === phase ? "is-active" : "")}`}>
                  <span className="phase-glyph">
                    {p.done ? <Icon.check /> : (i === phase ? <span className="spinner" /> : <span className="dot-pending" />)}
                  </span>
                  <span className="phase-label">{p.label}</span>
                </li>
              ))}
            </ul>
            <div className="modal-progress">
              <div className="modal-progress-fill" style={{ width: `${(phase / 3) * 100}%` }} />
            </div>
          </>
        ) : (
          <>
            <div className="success-mark"><Icon.check /></div>
            <h3 className="modal-title">{t.dep_done}</h3>
            <div className="url-card">
              <span className="url-label">{t.dep_url}</span>
              <div className="url-row">
                <Icon.globe />
                <code className="url-code">{url}</code>
                <button className="link-btn" onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }}>
                  <Icon.copy /> {copied ? t.dep_copied : t.dep_copy}
                </button>
              </div>
            </div>
            <div className="modal-actions">
              <button className="link-btn" onClick={onClose}>{t.dep_close}</button>
              <Btn variant="primary" onClick={() => onLive(url)}>{t.dep_open} <Icon.arrow /></Btn>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function LiveApp({ state, url, onBack, onRedeploy }) {
  const { t } = useT();
  return (
    <div className="live">
      <div className="live-bar">
        <button className="link-btn" onClick={onBack}><Icon.back /> {t.live_back}</button>
        <div className="live-url"><Icon.globe /><code>{url}</code></div>
        <Btn variant="ghost" onClick={onRedeploy}>{t.live_redeploy}</Btn>
      </div>
      <div className="live-stage">
        <LivePreview state={state} />
      </div>
    </div>
  );
}

function LivePreview({ state }) {
  const title = state.title || "untitled";
  if (state.projectType === "ai") {
    return (
      <div className="live-ai">
        <div className="live-ai-head">
          <div className="live-ai-avatar">{title[0]?.toUpperCase() || "A"}</div>
          <div>
            <div className="live-ai-name">{title}</div>
            <div className="live-ai-status">online · ready</div>
          </div>
        </div>
        <div className="live-ai-thread">
          <div className="bubble agent">Hola, soy {title}. {state.goal || "¿En qué puedo ayudarte?"}</div>
          <div className="bubble user">¿Cómo empezamos?</div>
          <div className="bubble agent">Cuéntame qué tienes en mente y avanzamos paso a paso.</div>
        </div>
        <div className="live-ai-input"><span>Escribe un mensaje…</span><span>↵</span></div>
      </div>
    );
  }
  if (state.projectType === "app") {
    return (
      <div className="live-app">
        <aside className="live-app-side">
          <div className="live-app-brand">{title}</div>
          <div className="live-app-nav">
            <span className="is-on">Inicio</span>
            <span>Proyectos</span>
            <span>Ajustes</span>
          </div>
        </aside>
        <main className="live-app-main">
          <h2>Hola otra vez 👋</h2>
          <p className="dim">{state.desc || "Aquí va un panel limpio para empezar."}</p>
          <div className="live-app-cards">
            <div className="card-soft"><h4>12</h4><span>elementos</span></div>
            <div className="card-soft"><h4>03</h4><span>activos</span></div>
            <div className="card-soft"><h4>87%</h4><span>salud</span></div>
          </div>
          <div className="live-app-table">
            <div className="lt-row lt-head"><span>Nombre</span><span>Estado</span><span>Hoy</span></div>
            <div className="lt-row"><span>Proyecto α</span><span className="ok">activo</span><span>+12</span></div>
            <div className="lt-row"><span>Proyecto β</span><span className="warn">en curso</span><span>+04</span></div>
            <div className="lt-row"><span>Proyecto γ</span><span>archivado</span><span>—</span></div>
          </div>
        </main>
      </div>
    );
  }
  if (state.projectType === "site") {
    return (
      <div className="live-site">
        <nav className="live-site-nav">
          <span className="brand-name">{title}</span>
          <span>inicio</span><span>sobre</span><span>contacto</span>
        </nav>
        <header className="live-site-hero">
          <h1>{state.goal || "Construido con calma."}</h1>
          <p>{state.desc || "Una colección de páginas pensadas para acompañar."}</p>
        </header>
        <section className="live-site-grid">
          <article><h4>Manifiesto</h4><p>Empezamos por las preguntas, no por las respuestas.</p></article>
          <article><h4>Trabajo</h4><p>Tres piezas recientes para enseñar cómo pensamos.</p></article>
          <article><h4>Contacto</h4><p>Escríbenos. Respondemos en menos de 48 horas.</p></article>
        </section>
      </div>
    );
  }
  // landing
  return (
    <div className="live-landing">
      <header className="ll-nav">
        <span className="brand-name">{title}</span>
        <span className="ll-cta">Empezar →</span>
      </header>
      <section className="ll-hero">
        <span className="pill pill-muted">— ahora en beta —</span>
        <h1 className="display">{state.goal || "Una idea simple, hecha bien."}</h1>
        <p className="lede">{state.desc || "Te acompañamos desde la pregunta inicial hasta el despliegue final."}</p>
        <div className="ll-actions">
          <button className="btn btn-primary">Probar gratis</button>
          <button className="btn btn-ghost">Ver demo</button>
        </div>
        <div className="ll-figure">
          <svg viewBox="0 0 600 200" width="100%" height="180">
            <defs>
              <pattern id="dotsL" width="14" height="14" patternUnits="userSpaceOnUse">
                <circle cx="1" cy="1" r="1" fill="currentColor" opacity="0.18" />
              </pattern>
            </defs>
            <rect width="600" height="200" fill="url(#dotsL)" />
            <path d="M20 160 C 140 30, 260 180, 380 80 S 540 130, 580 50" fill="none" stroke="var(--accent)" strokeWidth="1.6" />
          </svg>
        </div>
      </section>
      <section className="ll-three">
        <article><h4>Rápido</h4><p>De la idea al deploy en una sola sesión.</p></article>
        <article><h4>Tuyo</h4><p>Tu código, tu API key, tu dominio.</p></article>
        <article><h4>Acompañado</h4><p>Un tutor cerca cuando lo necesites.</p></article>
      </section>
    </div>
  );
}

function slug(s) {
  return (s || "").toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 28);
}

Object.assign(window, { DeployModal, LiveApp });
