/* ============================================================
   screen_migration.jsx — SEO-миграция при редизайне (M13) ⭐
   Wizard из 4 шагов
   ============================================================ */
function Migration({ ctx }) {
  const redesignSite = DATA.sites.find(s => s.status === "redesign") || DATA.sites.find(s => s.id === ctx.site);
  const [step, setStep] = React.useState(1);
  const steps = [
    { n: 1, label: "Снимок старого сайта", icon: "database" },
    { n: 2, label: "Карта редиректов", icon: "truck" },
    { n: 3, label: "Чек-лист запуска", icon: "check_circle" },
    { n: 4, label: "Мониторинг 30 дней", icon: "shield" },
  ];

  return (
    <div className="grid" style={{ gap: 18 }}>
      {/* site banner */}
      <div className="card card-pad" style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 18px" }}>
        <Favicon site={redesignSite} size={32} radius={8} />
        <div>
          <div style={{ fontSize: 14, fontWeight: 800 }}>{redesignSite.title}</div>
          <div style={{ fontSize: 12, color: "var(--ink-4)", fontWeight: 600 }}>{redesignSite.domain} · переезд на новый дизайн</div>
        </div>
        <span className="badge b-violet" style={{ marginLeft: 4 }}>на редизайне</span>
        <div style={{ flex: 1 }} />
        <div style={{ fontSize: 12.5, color: "var(--ink-2)", fontWeight: 600, textAlign: "right", maxWidth: 280 }}>
          <Icon name="alert_triangle" size={14} style={{ color: "var(--orange)", verticalAlign: "-2px", marginRight: 5 }} />
          Без правильной миграции теряются позиции, набранные годами.
        </div>
      </div>

      {/* stepper */}
      <div style={{ display: "flex", alignItems: "center", gap: 0, padding: "4px 6px" }}>
        {steps.map((s, i) => (
          <React.Fragment key={s.n}>
            <button onClick={() => setStep(s.n)} style={{ display: "flex", alignItems: "center", gap: 11, background: "none", border: "none", cursor: "pointer", padding: "4px 6px" }}>
              <span style={{ width: 38, height: 38, borderRadius: 12, flex: "0 0 38px", display: "flex", alignItems: "center", justifyContent: "center",
                background: step > s.n ? "var(--green)" : step === s.n ? "var(--accent)" : "var(--surface)",
                color: step >= s.n ? "#fff" : "var(--ink-4)", border: step < s.n ? "1px solid var(--border-strong)" : "none",
                transition: "all .2s", boxShadow: step === s.n ? "var(--sh-2)" : "none" }}>
                {step > s.n ? <Icon name="check_circle" size={20} /> : <Icon name={s.icon} size={19} />}
              </span>
              <span style={{ textAlign: "left" }}>
                <span style={{ display: "block", fontSize: 10.5, fontWeight: 700, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: ".04em" }}>Шаг {s.n}</span>
                <span style={{ display: "block", fontSize: 13, fontWeight: 700, color: step === s.n ? "var(--ink)" : "var(--ink-3)" }}>{s.label}</span>
              </span>
            </button>
            {i < steps.length - 1 && <div style={{ flex: 1, height: 2, background: step > s.n ? "var(--green)" : "var(--border)", margin: "0 6px", borderRadius: 2, transition: "background .3s" }} />}
          </React.Fragment>
        ))}
      </div>

      {step === 1 && <MigStep1 onNext={() => setStep(2)} />}
      {step === 2 && <MigStep2 onNext={() => setStep(3)} onBack={() => setStep(1)} />}
      {step === 3 && <MigStep3 onNext={() => setStep(4)} onBack={() => setStep(2)} />}
      {step === 4 && <MigStep4 site={redesignSite} onBack={() => setStep(3)} />}
    </div>
  );
}

function MigNav({ onBack, onNext, nextLabel = "Далее", backLabel = "Назад" }) {
  return (
    <div style={{ display: "flex", gap: 10, justifyContent: "space-between", marginTop: 4 }}>
      {onBack ? <button className="btn btn-ghost" onClick={onBack}><Icon name="chevron_left" size={16} />{backLabel}</button> : <span />}
      {onNext && <button className="btn btn-primary" onClick={onNext}>{nextLabel}<Icon name="arrow_right" size={16} /></button>}
    </div>
  );
}

function MigStep1({ onNext }) {
  const [scanned, setScanned] = React.useState(true);
  const urls = DATA.migration.oldUrls;
  const valuable = urls.filter(u => u.valuable).length;
  return (
    <div className="grid" style={{ gap: 16 }}>
      <div className="card">
        <div className="card-head">
          <Icon name="database" size={16} style={{ color: "var(--accent)" }} />
          <h3>Снимок старого сайта</h3>
          <div className="spacer" />
          <span className="badge b-green"><Icon name="check_circle" size={12} />Снято {urls.length} URL</span>
          <button className="btn btn-ghost btn-sm"><Icon name="refresh" size={14} />Пересканировать</button>
        </div>
        <div style={{ display: "flex", gap: 0 }}>
          <SummaryCell label="Всего страниц" value={urls.length} />
          <SummaryCell label="Ценных страниц" value={valuable} accent="var(--green-ink)" sub="с трафиком/позициями" />
          <SummaryCell label="Суммарный трафик" value="5 070 /мес" />
          <SummaryCell label="Зафиксировано мета" value={urls.length} sub="title, H1, description" />
        </div>
      </div>
      <div className="card">
        <table className="tbl">
          <thead><tr><th>Старый URL</th><th className="num">Трафик/мес</th><th className="num">Позиция</th><th>Статус</th></tr></thead>
          <tbody>
            {urls.map((u, i) => (
              <tr key={i}>
                <td style={{ fontFamily: "ui-monospace, monospace", fontSize: 12.5, fontWeight: 600 }}>{u.url}</td>
                <td className="num tnum" style={{ fontWeight: 700 }}>{u.traffic}</td>
                <td className="num"><PosPill pos={u.pos} /></td>
                <td>{u.valuable ? <span className="badge b-green"><Icon name="award" size={12} />ценная страница</span> : <span className="badge b-gray">обычная</span>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <MigNav onNext={onNext} nextLabel="Перейти к редиректам" />
    </div>
  );
}

function SummaryCell({ label, value, sub, accent }) {
  return (
    <div style={{ flex: 1, padding: "16px 20px", borderRight: "1px solid var(--border)" }}>
      <div style={{ fontSize: 11.5, fontWeight: 700, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: ".04em" }}>{label}</div>
      <div className="tnum" style={{ fontSize: 24, fontWeight: 800, marginTop: 6, color: accent || "var(--ink)" }}>{value}</div>
      {sub && <div style={{ fontSize: 11.5, color: "var(--ink-4)", marginTop: 2, fontWeight: 600 }}>{sub}</div>}
    </div>
  );
}

function MigStep2({ onNext, onBack }) {
  const [rows, setRows] = React.useState(() => DATA.migration.oldUrls.map(u => ({ ...u })));
  const [editing, setEditing] = React.useState(null);
  const mapped = rows.filter(r => r.newUrl).length;
  return (
    <div className="grid" style={{ gap: 16 }}>
      <div className="card">
        <div className="card-head">
          <Icon name="truck" size={16} style={{ color: "var(--accent)" }} />
          <h3>Карта редиректов</h3>
          <span className="badge b-blue" style={{ marginLeft: 4 }}><Icon name="sparkles" size={12} />Автосопоставление ИИ</span>
          <div className="spacer" />
          <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-3)" }}>{mapped}/{rows.length} сопоставлено</span>
          <button className="btn btn-ghost btn-sm"><Icon name="download" size={14} />Экспорт</button>
        </div>
        <table className="tbl">
          <thead><tr><th style={{ width: "38%" }}>Старый URL</th><th style={{ width: 40 }}></th><th>Новый URL</th><th className="num">Уверенность ИИ</th></tr></thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i}>
                <td style={{ fontFamily: "ui-monospace, monospace", fontSize: 12.5, fontWeight: 600 }}>
                  {r.url}{r.valuable && <span className="badge b-green" style={{ marginLeft: 8, height: 18, fontSize: 10 }}>ценная</span>}
                </td>
                <td style={{ color: "var(--ink-4)", textAlign: "center" }}><Icon name="arrow_right" size={16} /></td>
                <td>
                  {editing === i ? (
                    <input className="input" autoFocus value={r.newUrl} onChange={e => setRows(rs => rs.map((x, j) => j === i ? { ...x, newUrl: e.target.value } : x))}
                      onBlur={() => setEditing(null)} onKeyDown={e => e.key === "Enter" && setEditing(null)} style={{ height: 32, fontFamily: "ui-monospace, monospace", fontSize: 12.5 }} />
                  ) : r.newUrl ? (
                    <span onClick={() => setEditing(i)} style={{ fontFamily: "ui-monospace, monospace", fontSize: 12.5, fontWeight: 600, color: "var(--accent-ink)", cursor: "text", display: "inline-flex", alignItems: "center", gap: 6 }}>
                      {r.newUrl}<Icon name="edit" size={12} style={{ color: "var(--ink-4)" }} />
                    </span>
                  ) : (
                    <button className="btn btn-soft btn-sm" onClick={() => setEditing(i)}>Сопоставить вручную</button>
                  )}
                </td>
                <td className="num"><ConfBar conf={r.conf} mapped={!!r.newUrl} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="card card-pad" style={{ display: "flex", gap: 10, alignItems: "center" }}>
        <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--ink-3)" }}>Экспортировать как:</span>
        <button className="btn btn-ghost btn-sm"><Icon name="code" size={14} />.htaccess</button>
        <button className="btn btn-ghost btn-sm"><Icon name="code" size={14} />nginx.conf</button>
        <button className="btn btn-ghost btn-sm"><Icon name="wordpress" size={14} />WP Redirection</button>
      </div>
      <MigNav onBack={onBack} onNext={onNext} nextLabel="Перейти к чек-листу" />
    </div>
  );
}

function ConfBar({ conf, mapped }) {
  if (!mapped) return <span style={{ fontSize: 11.5, color: "var(--ink-4)", fontWeight: 700 }}>—</span>;
  const color = conf >= 85 ? "var(--green)" : conf >= 60 ? "var(--yellow)" : "var(--orange)";
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
      <span style={{ width: 54, height: 6, borderRadius: 99, background: "var(--bg-sunken)", overflow: "hidden" }}>
        <span style={{ display: "block", height: "100%", width: conf + "%", background: color, borderRadius: 99 }} />
      </span>
      <span className="tnum" style={{ fontSize: 12, fontWeight: 800, color, minWidth: 30 }}>{conf}%</span>
    </span>
  );
}

function MigStep3({ onNext, onBack }) {
  const items = DATA.migration.checklist;
  const stMeta = {
    ok: { badge: "b-green", icon: "check_circle", label: "проверено" },
    warn: { badge: "b-orange", icon: "alert_triangle", label: "проблема" },
    pending: { badge: "b-gray", icon: "clock", label: "проверяется" },
  };
  const ok = items.filter(i => i.status === "ok").length;
  const warn = items.filter(i => i.status === "warn").length;
  return (
    <div className="grid" style={{ gap: 16 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16 }}>
        <ResultTile color="var(--green)" big={ok} label="Проверок пройдено" icon="check_circle" />
        <ResultTile color="var(--orange)" big={warn} label="Требуют внимания" icon="alert_triangle" />
        <ResultTile color="var(--ink-4)" big={items.length - ok - warn} label="В процессе" icon="clock" />
      </div>
      <div className="card">
        <div className="card-head"><Icon name="check_circle" size={16} style={{ color: "var(--accent)" }} /><h3>Чек-лист запуска нового сайта</h3><div className="spacer" /><button className="btn btn-ghost btn-sm"><Icon name="refresh" size={14} />Перепроверить всё</button></div>
        {items.map((it, i) => {
          const m = stMeta[it.status];
          return (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 13, padding: "13px 18px", borderBottom: i === items.length - 1 ? "none" : "1px solid var(--border)" }}>
              <span style={{ color: m.badge === "b-green" ? "var(--green)" : m.badge === "b-orange" ? "var(--orange)" : "var(--ink-4)" }}><Icon name={m.icon} size={20} /></span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)" }}>{it.t}</div>
                {it.note && <div style={{ fontSize: 12, color: "var(--orange-ink)", fontWeight: 600, marginTop: 2 }}>{it.note}</div>}
              </div>
              {it.auto && <span className="badge b-gray" style={{ height: 19, fontSize: 10.5 }}><Icon name="bot" size={11} />авто</span>}
              <span className={"badge " + m.badge}>{m.label}</span>
              {it.status === "warn" && <button className="btn btn-soft btn-sm">Исправить</button>}
            </div>
          );
        })}
      </div>
      <MigNav onBack={onBack} onNext={onNext} nextLabel="Запустить мониторинг" />
    </div>
  );
}

function ResultTile({ color, big, label, icon }) {
  return (
    <div className="card card-pad" style={{ display: "flex", alignItems: "center", gap: 14 }}>
      <span style={{ width: 46, height: 46, borderRadius: 12, background: `color-mix(in srgb, ${color} 12%, white)`, color, display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 46px" }}><Icon name={icon} size={24} /></span>
      <div>
        <div className="tnum" style={{ fontSize: 28, fontWeight: 800, lineHeight: 1, color }}>{big}</div>
        <div style={{ fontSize: 12.5, color: "var(--ink-3)", fontWeight: 600, marginTop: 3 }}>{label}</div>
      </div>
    </div>
  );
}

function MigStep4({ site, onBack }) {
  // valuable pages position after launch — mostly stable, one dip recovering
  const before = [3, 5, 2, 4, 7];
  const series = DATA.migration.oldUrls.filter(u => u.valuable);
  const day = 12;
  const histories = series.map((s, idx) => {
    const arr = []; let v = s.pos;
    for (let i = 0; i < 30; i++) {
      if (i < 3) arr.push(v);
      else if (i < 8) { v = s.pos + (idx === 2 ? 6 : idx === 0 ? 3 : 1); arr.push(Math.round(v)); }
      else { v += (s.pos - v) * 0.3; arr.push(Math.max(1, Math.round(v))); }
    }
    return arr;
  });
  const colors = ["var(--accent)", "var(--green)", "var(--orange)", "var(--violet)", "var(--blue)"];
  return (
    <div className="grid" style={{ gap: 16 }}>
      <div className="card card-pad" style={{ background: "linear-gradient(100deg, var(--green-soft), var(--surface) 65%)", borderColor: "#CDEAD9", display: "flex", alignItems: "center", gap: 16 }}>
        <span style={{ width: 46, height: 46, borderRadius: 12, background: "var(--green)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 46px" }}><Icon name="shield" size={24} /></span>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 15, fontWeight: 800 }}>Идёт {day}-й день мониторинга из 30</div>
          <div style={{ fontSize: 13, color: "var(--ink-2)", fontWeight: 500, marginTop: 2 }}>Ценные страницы под наблюдением. Большинство позиций восстановилось — миграция проходит штатно.</div>
        </div>
        <div style={{ textAlign: "center" }}>
          <div className="tnum" style={{ fontSize: 26, fontWeight: 800, color: "var(--green-ink)" }}>4/5</div>
          <div style={{ fontSize: 11, color: "var(--ink-4)", fontWeight: 700, textTransform: "uppercase" }}>восстановлено</div>
        </div>
      </div>
      <div className="card">
        <div className="card-head"><Icon name="trending" size={16} style={{ color: "var(--accent)" }} /><h3>Позиции ценных страниц после запуска</h3><div className="spacer" /><span style={{ fontSize: 11.5, color: "var(--ink-4)", fontWeight: 600 }}>⌁ день запуска нового сайта</span></div>
        <div className="card-pad">
          <LineChart series={series.map((s, i) => ({ name: s.url, data: histories[i], color: colors[i] }))} updates={[{ day: 3, label: "Запуск" }]} height={220} maxY={20} />
        </div>
      </div>
      <div className="card">
        <div className="card-head"><Icon name="bell" size={16} style={{ color: "var(--accent)" }} /><h3>Алерты потерь</h3></div>
        <div style={{ display: "flex", alignItems: "center", gap: 13, padding: "13px 18px", borderBottom: "1px solid var(--border)" }}>
          <span className="dot d-orange" />
          <div style={{ flex: 1, fontSize: 13.5, fontWeight: 600 }}>/karkasnye-doma просела с 2 на 8 в первые дни — сейчас восстанавливается (текущая позиция 3)</div>
          <span className="badge b-green">восстанавливается</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 13, padding: "13px 18px" }}>
          <span className="dot d-green" />
          <div style={{ flex: 1, fontSize: 13.5, fontWeight: 600, color: "var(--ink-2)" }}>Остальные 4 ценные страницы держат позиции в пределах нормы</div>
          <span className="badge b-green"><Icon name="check_circle" size={12} />в порядке</span>
        </div>
      </div>
      <MigNav onBack={onBack} />
    </div>
  );
}

window.Migration = Migration;
