// Repo Creator — connects to real /create and /check-name endpoints
const { useState, useEffect, useRef, useMemo, useCallback } = React;

const STAGES = [
  { name: 'Validate', pct: 20 },
  { name: 'Compose',  pct: 50 },
  { name: 'Push',     pct: 80 },
  { name: 'Topics',   pct: 95 },
];

const TERMINAL_LINES = [
  { d: 0,    p: '$', t: 'devex create --interactive', cls: 'br' },
  { d: 280,  p: '›', t: 'validating repository name…', cls: 'dim' },
  { d: 720,  p: '✓', t: 'name available', cls: 'ok' },
  { d: 1100, p: '›', t: 'composing service manifest', cls: 'dim' },
  { d: 1500, p: '+', t: 'docker-compose.yml', cls: 'ok' },
  { d: 1700, p: '+', t: '.github/workflows/deploy.yml', cls: 'ok' },
  { d: 2200, p: '›', t: 'pushing to github…', cls: 'dim' },
  { d: 3200, p: '✓', t: 'remote: ref refs/heads/main updated', cls: 'ok' },
  { d: 3500, p: '›', t: 'tagging topics: devex, vps', cls: 'dim' },
  { d: 4000, p: '✓', t: 'topics applied', cls: 'ok' },
  { d: 4300, p: '✓', t: 'ready · done', cls: 'br' },
];

function Creator({ tweaks, onOpenReadme, onTriggerConfetti }) {
  const { SERVICES, TEMPLATES, randName } = window.DEVEX_DATA;
  const I = window.I;

  const [tab, setTab] = useState('app');
  const [name, setName] = useState(() => randName());
  const [validation, setValidation] = useState('checking');
  const [shuffleSpin, setShuffleSpin] = useState(false);
  const [selected, setSelected] = useState(SERVICES.length > 0 ? [SERVICES[0].id] : []);
  const [template, setTemplate] = useState(TEMPLATES.length > 0 ? TEMPLATES[0].id : '');
const [topics, setTopics] = useState(true);
  const [phase, setPhase] = useState('idle');
  const [progress, setProgress] = useState(0);
  const [stageIdx, setStageIdx] = useState(-1);
  const [logLines, setLogLines] = useState([]);
  const [createdData, setCreatedData] = useState(null);
  const [createError, setCreateError] = useState(null);
  const pollRef = useRef(null);

  // Real name check via /check-name
  useEffect(() => {
    if (tweaks.demoValidation && tweaks.demoValidation !== 'auto') {
      setValidation(tweaks.demoValidation);
      return;
    }
    if (!name.trim()) { setValidation('invalid'); return; }
    setValidation('checking');
    const ctrl = new AbortController();
    const t = setTimeout(async () => {
      try {
        const r = await fetch(`/check-name?name=${encodeURIComponent(name)}`, { signal: ctrl.signal });
        const data = await r.json();
        if (!data.valid) setValidation('invalid');
        else if (data.available === false) setValidation('invalid');
        else setValidation('valid');
      } catch (err) {
        if (err.name !== 'AbortError') setValidation('valid'); // allow if offline check fails
      }
    }, 450);
    return () => { clearTimeout(t); ctrl.abort(); };
  }, [name, tweaks.demoValidation]);

  useEffect(() => {
    if (tweaks.demoPhase && tweaks.demoPhase !== 'auto') {
      if (tweaks.demoPhase === 'creating') { setPhase('creating'); setProgress(60); setStageIdx(2); }
      else if (tweaks.demoPhase === 'success') jumpSuccess();
      else if (tweaks.demoPhase === 'idle') resetAll();
    }
  }, [tweaks.demoPhase]);

  const toggleService = (id) => {
    if (phase !== 'idle') return;
    setSelected(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);
  };

  const doShuffle = () => {
    setShuffleSpin(true);
    setName(randName());
    setTimeout(() => setShuffleSpin(false), 420);
  };

  const resetAll = () => {
    setPhase('idle');
    setProgress(0);
    setStageIdx(-1);
    setLogLines([]);
    setCreatedData(null);
    setCreateError(null);
    if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; }
  };

  const jumpSuccess = () => {
    const userLogin = window.DEVEX_INIT?.user?.login || 'org';
    setPhase('success');
    setProgress(100);
    setStageIdx(STAGES.length - 1);
    setLogLines(TERMINAL_LINES);
    setCreatedData({ repo_url: `https://github.com/${userLogin}/${name}`, app_name: name });
  };

  const startCreate = async (silent = false) => {
    if (phase !== 'idle') return;
    setPhase('creating');
    setProgress(5);
    setStageIdx(0);
    setLogLines([]);
    setCreatedData(null);
    setCreateError(null);

    // Optimistic progress animation
    const ANIM = [
      { d: 400,  pct: 20, idx: 0 },
      { d: 1400, pct: 48, idx: 1 },
      { d: 2800, pct: 72, idx: 2 },
    ];
    const timers = ANIM.map(s => setTimeout(() => { setProgress(s.pct); setStageIdx(s.idx); }, s.d));
    TERMINAL_LINES.forEach(line => {
      timers.push(setTimeout(() => setLogLines(prev => [...prev, line]), line.d));
    });

    const formData = new FormData();
    formData.append('app_name', name);
    formData.append('description', '');
    if (tab === 'app') {
      formData.append('project_type', 'vps');
      selected.forEach(id => formData.append('service_type', id));
    } else {
      formData.append('project_type', 'repo-template');
      formData.append('repo_template', template);
    }

    try {
      const r = await fetch('/create', {
        method: 'POST',
        headers: { 'X-Devex-SPA': '1' },
        body: formData,
      });
      timers.forEach(clearTimeout);

      const json = await r.json();

      if (!r.ok && !json.pending) {
        setCreateError(json.error || 'Creation failed. Please try again.');
        setPhase('idle');
        setProgress(0);
        return;
      }

      setProgress(90);
      setStageIdx(2);

      if (json.pending) {
        // Repo template flow — poll
        setProgress(95);
        setStageIdx(3);
        let attempts = 0;
        const MAX = 60;
        pollRef.current = setInterval(async () => {
          attempts++;
          try {
            const pr = await fetch(`/check-repo-ready?owner=${encodeURIComponent(json.owner)}&repo=${encodeURIComponent(json.repo)}`);
            const pj = await pr.json();
            if (pj.ready) {
              clearInterval(pollRef.current); pollRef.current = null;
              setProgress(100); setStageIdx(STAGES.length - 1);
              setCreatedData(json);
              setPhase('success');
              if (!silent) onTriggerConfetti();
            }
          } catch (_) {}
          if (attempts >= MAX) {
            clearInterval(pollRef.current); pollRef.current = null;
            setCreatedData(json);
            setPhase('success');
            if (!silent) onTriggerConfetti();
          }
        }, 3000);
      } else {
        setProgress(100);
        setStageIdx(STAGES.length - 1);
        setCreatedData(json);
        setPhase('success');
        if (!silent) onTriggerConfetti();
      }
    } catch (err) {
      timers.forEach(clearTimeout);
      setCreateError('Network error. Please try again.');
      setPhase('idle');
      setProgress(0);
    }
  };

  useEffect(() => () => { if (pollRef.current) clearInterval(pollRef.current); }, []);

  const submitDisabled =
    phase !== 'idle' ||
    validation !== 'valid' ||
    (tab === 'app' && selected.length === 0) ||
    (tab === 'template' && !template);

  if (phase === 'success') {
    return <SuccessCard
      name={name}
      tab={tab}
      selected={selected}
      template={template}
      onCreateAnother={resetAll}
      createdData={createdData}
    />;
  }

  return (
    <div className="card slide-up" data-tour="creator">
      <div className="card-head">
        <div className="card-title"><span className="pre">▍</span> New Repository</div>
        <div className="hint">esc to cancel</div>
      </div>

      {/* Tabs */}
      <div style={{ padding: 18, paddingBottom: 0 }}>
        <div className="tabs" data-tour="tabs">
          <button className={`tab ${tab === 'app' ? 'active' : ''}`} onClick={() => setTab('app')}>
            <span className="tab-num">01</span><span>App · VPS</span>
          </button>
          <button className={`tab ${tab === 'template' ? 'active' : ''}`} onClick={() => setTab('template')}>
            <span className="tab-num">02</span><span>Repo Template</span>
          </button>
        </div>
      </div>

      <div className="card-body" style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>

        {/* Name field */}
        <div className="field" data-tour="name">
          <div className="field-label">
            <span>Repo Name</span>
            <span className="right">{(window.DEVEX_INIT?.user?.login || 'org')}/<span style={{ color: 'var(--accent)' }}>{name || '…'}</span></span>
          </div>
          <div className={`input-wrap state-${validation}`}>
            <span className="input-prefix">{(window.DEVEX_INIT?.user?.login || 'org')}/</span>
            <input
              className="input"
              value={name}
              spellCheck={false}
              autoComplete="off"
              onChange={e => setName(e.target.value.toLowerCase().replace(/\s+/g, '-'))}
              placeholder="adjective-noun"
              aria-label="Repository name"
            />
            <div className="input-suffix">
              <span className={`input-status ${validation}`}>
                {validation === 'checking' && '○ checking'}
                {validation === 'valid'    && '● available'}
                {validation === 'invalid'  && '✕ taken'}
              </span>
              <button className={`shuffle-btn ${shuffleSpin ? 'spin' : ''}`} onClick={doShuffle} title="Random name">
                <span className="shuffle-icon" style={{ display: 'inline-flex' }}><I.Shuffle size={14} /></span>
                Shuffle
              </button>
            </div>
          </div>
          <div className="hint" style={{ marginTop: 4 }}>
            {validation === 'invalid'
              ? <span className="hint error">// name conflicts with existing repo or violates [a-z0-9-] policy</span>
              : <span>// kebab-case · 3-40 chars · the URL slug</span>}
          </div>
        </div>

{/* Tab content */}
        {tab === 'app' ? (
          <div className="field" data-tour="services">
            <div className="field-label">
              <span>Services <span style={{ color: 'var(--accent)' }}>· {selected.length} selected</span></span>
              <span className="right">click to toggle</span>
            </div>
            <div className="service-grid">
              {SERVICES.map(s => {
                const Glyph = I[s.icon];
                const isSel = selected.includes(s.id);
                return (
                  <div key={s.id}
                       className={`service ${isSel ? 'selected' : ''}`}
                       onClick={() => toggleService(s.id)}>
                    <div className="service-check">
                      {isSel && <I.Check size={12} />}
                    </div>
                    <div className="service-icon">{Glyph && <Glyph size={24} />}</div>
                    <div className="service-name">{s.name}</div>
                    <div className="service-desc">{s.desc}</div>
                    <div className="service-tag">{s.tag}</div>
                  </div>
                );
              })}
            </div>
          </div>
        ) : (
          <div className="field">
            <div className="field-label"><span>Choose a template</span></div>
            <div className="template-grid">
              {TEMPLATES.map(t => (
                <div key={t.id}
                     className={`template ${template === t.id ? 'selected' : ''}`}
                     onClick={() => setTemplate(t.id)}>
                  <div className="template-head">
                    <I.Cube size={20} />
                    <div className="template-name">{t.name}</div>
                    {template === t.id && (
                      <div style={{ marginLeft: 'auto', color: 'var(--accent)' }}>
                        <I.Check size={16} />
                      </div>
                    )}
                  </div>
                  <div className="template-desc">{t.desc}</div>
                  {t.stack && t.stack.length > 0 && (
                    <div className="template-stack">
                      {t.stack.map(s => <span key={s} className="stack-chip">{s}</span>)}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Topics toggle */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', border: '1px solid var(--border)', padding: '12px 14px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <I.Tag size={14} />
            <div style={{ fontSize: 12, fontWeight: 600 }}>Auto-tag with topics</div>
          </div>
          <button
            onClick={() => setTopics(t => !t)}
            style={{ width: 36, height: 20, padding: 0, background: topics ? 'var(--accent)' : 'var(--surface-2)', border: '1px solid ' + (topics ? 'var(--accent)' : 'var(--border)'), position: 'relative' }}
            aria-pressed={topics} aria-label="Toggle auto-tag topics"
          >
            <span style={{ position: 'absolute', top: 1, bottom: 1, left: topics ? 17 : 1, width: 16, background: '#fff', transition: 'left 160ms' }}/>
          </button>
        </div>

        {/* Progress (creating phase) */}
        {phase === 'creating' && (
          <div className="progress slide-up" data-tour="progress">
            <div className="progress-head">
              <span>creating · {STAGES[stageIdx]?.name || 'init'}</span>
              <span className="pct">{progress}%</span>
            </div>
            <div className="progress-track">
              <div className="progress-fill" style={{ width: progress + '%' }}/>
            </div>
            <div className="progress-stages">
              {STAGES.map((s, i) => (
                <div key={s.name} className={`stage ${i < stageIdx ? 'done' : i === stageIdx ? 'active' : ''}`}>
                  <div className="stage-name">
                    <span>{i < stageIdx ? '✓' : i === stageIdx ? '›' : '○'}</span>
                    {s.name}
                  </div>
                  <div className="stage-pct">{i <= stageIdx ? `${i === stageIdx ? progress : s.pct}%` : '—'}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Error state */}
        {createError && (
          <div style={{ padding: '12px 14px', border: '1px solid var(--accent)', background: 'var(--accent-tint)', fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--accent)', display: 'flex', alignItems: 'center', gap: 8 }}>
            <I.X size={14}/> {createError}
          </div>
        )}

        {/* Preview README action */}
        <div className="float-actions">
          <button className="ghost-btn" onClick={onOpenReadme}>
            <I.Doc size={14} /> Preview README
          </button>
        </div>

        {/* CTA */}
        <button
          className="cta"
          disabled={submitDisabled}
          onClick={() => startCreate(false)}
          data-tour="submit"
        >
          <span className="cta-main">
            {phase === 'creating'
              ? <>creating<span className="terminal-cursor" style={{ background: '#fff' }}/></>
              : <>Create Repository <I.Arrow size={14} /></>}
          </span>
        </button>
      </div>
    </div>
  );
}

function SuccessCard({ name, tab, selected, template, onCreateAnother, createdData }) {
  const I = window.I;
  const userLogin = window.DEVEX_INIT?.user?.login || 'org';
  const repoUrl = createdData?.repo_url || `https://github.com/${userLogin}/${name}`;
  const displayUrl = repoUrl.replace('https://', '');
  return (
    <div className="success slide-up">
      <div className="success-banner">
        <div className="checkmark"><I.Check size={22} /></div>
        <div>
          <div className="success-title">Repository pushed</div>
          <div className="success-sub">{userLogin}/{name} · {tab === 'app' ? `${selected.length} services` : template} · ready</div>
        </div>
      </div>

      <pre className="ascii">{`
   ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
   ┃   ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░   ┃
   ┃   ░  D E P L O Y M E N T   C O M P L E T E  ░   ┃
   ┃   ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░   ┃
   ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛`}</pre>

      <div className="success-grid">
        <div className="success-cell">
          <div className="k">URL</div>
          <div className="v" style={{ color: 'var(--accent)' }}>{displayUrl}</div>
        </div>
        <div className="success-cell">
          <div className="k">Default branch</div>
          <div className="v">main</div>
        </div>
        <div className="success-cell">
          <div className="k">Type</div>
          <div className="v">{tab === 'app' ? 'VPS service' : 'Repo template'}</div>
        </div>
        <div className="success-cell">
          <div className="k">Topics</div>
          <div className="v">devex · {tab === 'app' ? 'vps' : 'starter'}</div>
        </div>
      </div>

      <div className="success-cta">
        <button className="primary" onClick={() => window.open(repoUrl, '_blank')}>
          <I.ExternalLink size={14} /> Open Repository
        </button>
        <button onClick={onCreateAnother}>
          <I.Plus size={14} /> Create Another
        </button>
      </div>
    </div>
  );
}

window.Creator = Creator;
window.SuccessCard = SuccessCard;
window.TERMINAL_LINES = TERMINAL_LINES;
