/* ──────────────────────────────────────────────────────────────
   Topic Mock — phone-frame container with two tabs.
   - Операторская (default): General c KPI + 4 системных топика. Без скролла, фиксированный список.
   - Открытые линии:           General (без статистики) + клиентские топики, скролл внутри фрейма.
                               Клик по топику → справа открывается диалог (desktop)
                                              или подменяет список (mobile).
────────────────────────────────────────────────────────────── */

const OPS_VIEW = [
  { kind: "general", title: "General", inline: null, author: "TelegaFirst", preview: "💰 7 / 104 930 ₽  ·  📥 23 заявки  ·  🤖 198 диалогов", date: "сегодня", pin: true, icon: "#" },
  { kind: "topic", title: "Обращения",        inline: "⏳ 4",            author: null,                preview: "Анна Петрова: «хочу курс по дизайну»", date: "14:32", badge: 4, bg: "#2aabee", icon: "О" },
  { kind: "topic", title: "Активные чаты",    inline: "💬 9",            author: "TelegaFirst Apollo", preview: "9 диалогов AI · 3 оператор",            date: "14:28", badge: 1, bg: "#2aabee", icon: "А" },
  { kind: "topic", title: "Оплаты",           inline: "💰 7/104 930₽",  author: "TelegaFirst Apollo", preview: "#RUB · 14 990 ₽ · AI Coach · №142",      date: "14:21", pin: true, bg: "#9b59b6", icon: "О" },
  { kind: "topic", title: "Заказы",           inline: "⏳ 3 / 💬 0",     author: null,                preview: "Екатерина Орлова — оформляет заказ",    date: "13:54", badge: 5, bg: "#f39c12", icon: "З" },
];

const OL_VIEW = [
  { kind: "general", ch: null,   title: "General",          inline: null,                author: null,                preview: "Общий чат группы",                       date: "пн",   icon: "#" },
  { kind: "topic",   ch: "tg",   title: "Анна Петрова",      username: "@anna_p",          inline: "💰 1/4 990₽",       author: "TelegaFirst Apollo", preview: "Уточняет уровень курса · AI ведёт",    date: "14:32", badge: 3, bg: "#2aabee", icon: "А" },
  { kind: "topic",   ch: "vk",   title: "Михаил Сидоров",   username: "id4827331",        inline: "💰 3/14 990₽  +2",  author: "TelegaFirst Apollo", preview: "✓ Оплата прошла · доступ выдан",       date: "14:28", bg: "#16a085", icon: "М" },
  { kind: "topic",   ch: "max",  title: "Екатерина Орлова", username: "@kate_o",          inline: "💰 0/0₽",            author: "TelegaFirst Apollo", preview: "Спросила про слоты на пятницу",        date: "14:21", badge: 1, bg: "#f39c12", icon: "Е" },
  { kind: "topic",   ch: "tg",   title: "Дмитрий Лебедев",  username: "@dmitry_l",        inline: "💰 1/4 990₽",       author: "Лена · оператор",     preview: "Лена забрала диалог",                  date: "13:42", bg: "#6c5ce7", icon: "Д" },
  { kind: "topic",   ch: "vk",   title: "Ольга Кравцова",   username: "id9183024",        inline: "💰 2/9 980₽  +1",   author: "TelegaFirst Apollo", preview: "Беру комплект — куда оплачивать?",     date: "13:18", badge: 2, bg: "#d63384", icon: "О" },
  { kind: "topic",   ch: "max",  title: "Алексей Громов",   username: "@alex_g",          inline: "💰 4/22 470₽  +3",  author: "TelegaFirst Apollo", preview: "Спасибо, всё работает!",                date: "12:54", bg: "#0f1419", icon: "А" },
  { kind: "topic",   ch: "tg",   title: "Виктория Зайцева", username: "@vika_z",          inline: "💰 0/0₽",            author: "TelegaFirst Apollo", preview: "Это можно для дочки 8 лет?",            date: "11:21", badge: 1, bg: "#16a085", icon: "В" },
];

const ANNA_CHAT = [];

const ChIcon = ({ ch }) => {
  if (!ch) return null;
  if (ch === "tg") return (
    <span className="tgsg-ch tg" title="Telegram">
      <svg width="11" height="11" viewBox="0 0 24 24" fill="none">
        <path d="M21.9 4.3L18.4 20c-.3 1.1-.9 1.4-1.9.9l-5.1-3.8-2.5 2.4c-.3.3-.5.5-1 .5l.3-5.1L18 6.5c.4-.4-.1-.6-.7-.2L7.1 12.5l-5-1.6c-1-.3-1.1-1 .2-1.5l18.5-7.1c.9-.3 1.6.2 1.3 1.5z" fill="white"/>
      </svg>
    </span>
  );
  if (ch === "vk") return (
    <span className="tgsg-ch vk" title="VK">
      <svg width="13" height="13" viewBox="0 0 24 24" fill="white">
        <path d="M2 5.5C2 4.1 3.1 3 4.5 3h15C20.9 3 22 4.1 22 5.5v13c0 1.4-1.1 2.5-2.5 2.5h-15C3.1 21 2 19.9 2 18.5v-13zm15.5 11.3c-.4-.7-1.8-2.6-2.4-3.3-.3-.4-.3-.5 0-.9.3-.4 1.6-2.1 2-2.8.3-.5.2-1-.3-1H15c-.4 0-.7.2-.9.6-.4.9-1.3 2.4-1.7 2.9-.3.4-.6.3-.6-.1V9.5c0-.5-.3-.7-.7-.7h-2c-.5 0-.8.3-.8.5 0 .4.6.5.7 1.6v2.3c0 .6-.2.7-.6.3-.8-.8-1.9-2.5-2.4-3.7-.2-.4-.5-.5-.9-.5H4.6c-.4 0-.6.2-.4.7C5.3 12.4 7.5 17 11 17h1.4c.4 0 .5-.2.5-.6v-1.6c0-.4.2-.6.5-.4.4.3 1.7 1.9 2 2.4.3.3.5.6 1 .6h2.1c.5 0 .6-.3.4-.6z"/>
      </svg>
    </span>
  );
  if (ch === "max") return (
    <span className="tgsg-ch max" title="Max">M</span>
  );
  return null;
};

const Row = ({ r }) => (
  <div className={`tgsg-row ${r.kind === "general" ? "general" : ""}`}>
    <div className={`tgsg-ava ${r.kind === "general" ? "hash" : ""}`}
         style={r.bg ? { background: r.bg } : {}}>
      {r.icon}
      {r.ch && <ChIcon ch={r.ch}/>}
    </div>
    <div className="tgsg-body">
      <div className="tgsg-line1">
        <span className="tgsg-title">
          {r.title}
          {r.username && <span className="tgsg-username"> {r.username}</span>}
          {r.inline && <span className="tgsg-inline"> ({r.inline})</span>}
        </span>
        <span className="tgsg-date">{r.date}</span>
      </div>
      <div className="tgsg-line2">
        {r.author && <span className="tgsg-author">{r.author}</span>}
        {r.author && r.preview && <span className="tgsg-author-sep">: </span>}
        <span className="tgsg-preview">{r.preview}</span>
      </div>
    </div>
    <div className="tgsg-right">
      {r.badge && <span className="tgsg-badge">{r.badge}</span>}
      {r.pin && <span className="tgsg-pin">📌</span>}
      {r.mention && <span className="tgsg-mention">@</span>}
    </div>
  </div>
);

const ChatPanel = ({ topic, onBack }) => (
  <div className="tgsg-chat">
    <div className="tgsg-chat-head">
      <button className="tgsg-chat-back" onClick={onBack}>‹</button>
      <div className="tgsg-ava sm" style={{ background: topic.bg }}>{topic.icon}</div>
      <div className="tgsg-chat-head-text">
        <div className="tgsg-chat-head-name">{topic.title}</div>
        <div className="tgsg-chat-head-meta">{topic.username} · {topic.inline}</div>
      </div>
    </div>
    <div className="tgsg-chat-body">
      {ANNA_CHAT.map((m, i) => {
        if (m.from === "card") return (
          <div key={i} className="tgsg-card-msg">
            <div className="tgsg-card-img">🎨</div>
            <div className="tgsg-card-text">
              <div className="tgsg-card-name">{m.title}</div>
              <div className="tgsg-card-desc">{m.desc}</div>
              <div className="tgsg-card-price">{m.price}</div>
              <button className="tgsg-card-buy">Купить</button>
            </div>
          </div>
        );
        return (
          <div key={i} className={`tgsg-msg ${m.from}`}>
            <span>{m.text}</span>
            <span className="tgsg-msg-time">{m.time}</span>
          </div>
        );
      })}
    </div>
    <div className="tgsg-chat-input">
      <span className="tgsg-chat-input-hint">оператор пишет /menu — получает кнопки управления</span>
    </div>
  </div>
);

const TopicMockSwitcher = ({ size = "lg" }) => {
  const [tab, setTab] = React.useState("ops");
  const list = tab === "ops" ? OPS_VIEW : OL_VIEW;

  return (
    <div className={`tgsg tgsg-${size}`}>
      {/* tab switcher */}
      <div className="tgsg-tabs">
        <button className={`tgsg-tab ${tab === "ops" ? "active" : ""}`} onClick={() => setTab("ops")}>
          🗂 Операторская
          <span className={`tgsg-tab-c ${tab === "ops" ? "" : "muted"}`}>{OPS_VIEW.length}</span>
        </button>
        <button className={`tgsg-tab ${tab === "ol" ? "active" : ""}`} onClick={() => setTab("ol")}>
          💬 Открытые линии
          <span className={`tgsg-tab-c ${tab === "ol" ? "" : "muted"}`}>{OL_VIEW.length}</span>
        </button>
      </div>

      {/* phone-like frame, fixed height */}
      <div className="tgsg-frame">
        {/* status bar */}
        <div className="tgsg-frame-status">
          <span>9:41</span>
          <span className="tgsg-frame-status-icons"><span>●●●</span></span>
        </div>
        {/* group title bar */}
        <div className="tgsg-frame-titlebar">
          <span className="tgsg-frame-back">‹</span>
          <div className="tgsg-frame-title-ava">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8z" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div className="tgsg-frame-titletxt">
            <div className="tgsg-frame-title">Мой бизнес</div>
            <div className="tgsg-frame-sub">
              {tab === "ops" ? "Операторская · 5 топиков" : "Открытые линии · 8 топиков"}
            </div>
          </div>
        </div>

        <div className="tgsg-frame-content">
          <div className={`tgsg-list ${tab === "ops" ? "no-scroll" : ""}`}>
            {list.map((r, i) => <Row key={i} r={r}/>)}
          </div>
        </div>
      </div>

      <div className="tgsg-foot">
        <span className="tgsg-foot-dot"/>
        {tab === "ops"
          ? "KPI бизнеса — в General, ниже 4 системных топика"
          : "Диалоги из Telegram, VK и Max — в одном списке"}
      </div>
    </div>
  );
};

window.TopicMockSwitcher = TopicMockSwitcher;
