/* eslint-disable */
// Editor — left-side form panel for RCS Studio

const MESSAGE_TYPES = [
  { id: "text", icon: I.Type, label: "純文字", en: "Text + quick reply", sub: "+ 快速回覆" },
  { id: "rich", icon: I.Square, label: "豐富卡片", en: "Rich card", sub: "圖+標+按鈕" },
  { id: "carousel", icon: I.Squares, label: "輪播卡片", en: "Carousel", sub: "多張可滑動" },
  { id: "media", icon: I.Film, label: "媒體訊息", en: "Media", sub: "圖片 / 影片" },
];

const ACTION_TYPES = [
  { id: "reply", label: "快速回覆", icon: I.Reply, en: "Quick reply" },
  { id: "url", label: "開啟網址", icon: I.Link, en: "Open URL" },
  { id: "call", label: "撥打電話", icon: I.Phone, en: "Call" },
  { id: "map", label: "查看地圖", icon: I.MapPin, en: "Show map" },
  { id: "calendar", label: "加入行事曆", icon: I.CalendarPlus, en: "Add to cal" },
];

function ActionRow({ action, onChange, onRemove }) {
  const type = ACTION_TYPES.find((t) => t.id === action.type) || ACTION_TYPES[0];
  return (
    <div className="action-item">
      <span className="drag"><I.Drag size={14} /></span>
      <div style={{ display: "flex", gap: 6, alignItems: "center", minWidth: 0 }}>
        <span className="icon-pick" style={{ width: 28, height: 28 }}><type.icon size={14} /></span>
        <input
          className="input-inline"
          value={action.label}
          placeholder="按鈕文字"
          onChange={(e) => onChange({ ...action, label: e.target.value })}
          style={{ flex: 1, minWidth: 0 }}
        />
      </div>
      <div style={{ display: "flex", gap: 4, alignItems: "center", minWidth: 0 }}>
        <select
          className="select-inline"
          value={action.type}
          onChange={(e) => onChange({ ...action, type: e.target.value })}
        >
          {ACTION_TYPES.map((t) => <option key={t.id} value={t.id}>{t.label}</option>)}
        </select>
        <input
          className="input-inline"
          value={action.target || ""}
          placeholder={action.type === "url" ? "https://..." : action.type === "call" ? "+886-2-..." : "值"}
          onChange={(e) => onChange({ ...action, target: e.target.value })}
          style={{ flex: 1, minWidth: 0 }}
        />
      </div>
      <button className="remove" onClick={onRemove}><I.X size={13} /></button>
    </div>
  );
}

function ActionsEditor({ items, onChange, max = 4, title = "互動按鈕", desc, allowedTypes }) {
  const types = allowedTypes || ACTION_TYPES;
  const update = (i, v) => {
    const next = [...items]; next[i] = v; onChange(next);
  };
  const remove = (i) => onChange(items.filter((_, idx) => idx !== i));
  const add = (t) => {
    if (items.length >= max) return;
    onChange([...items, { type: t, label: "", target: "" }]);
  };
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
        <div>
          <div style={{ fontSize: 12, fontWeight: 800 }}>{title}</div>
          {desc && <div style={{ fontSize: 11, color: "var(--rh-fg-muted)", marginTop: 2 }}>{desc}</div>}
        </div>
        <div style={{ fontSize: 11, fontWeight: 700, color: "var(--rh-fg-muted)" }}>{items.length} / {max}</div>
      </div>
      <div className="action-list">
        {items.map((a, i) => (
          <ActionRow key={i} action={a} onChange={(v) => update(i, v)} onRemove={() => remove(i)} />
        ))}
      </div>
      {items.length < max && (
        <div>
          <div className="suggested-types">
            {types.map((t) => (
              <button key={t.id} className="suggested-type" onClick={() => add(t.id)}>
                <t.icon size={14} />
                <span>{t.label}</span>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function MediaPicker({ value, onChange, allowVideo = false }) {
  const presets = [
    { k: "ramen", label: "拉麵" },
    { k: "shoes", label: "球鞋" },
    { k: "watch", label: "手錶" },
    { k: "coffee", label: "咖啡" },
    { k: "headphones", label: "耳機" },
  ];
  const hasMedia = !!value.preset;
  return (
    <div className={"media-upload" + (hasMedia ? " has-media" : "")}>
      {hasMedia ? (
        <div className="media-thumb"
          style={{ backgroundImage: `url(${MEDIA_PRESETS[value.preset]})` }} />
      ) : (
        <>
          <div style={{ width: 40, height: 40, borderRadius: "50%", background: "var(--rh-primary-tint)",
                        color: "var(--rh-primary)", display: "grid", placeItems: "center" }}>
            <I.Upload size={18} />
          </div>
          <div>
            <div className="upload-cta">拖曳上傳 / 從素材庫選擇</div>
            <p>支援 JPG、PNG、MP4，建議 1440×800 / 2MB 內</p>
          </div>
        </>
      )}
      <div className="gallery-preset">
        {presets.map((p) => (
          <button
            key={p.k}
            className={value.preset === p.k ? "active" : ""}
            style={{ backgroundImage: `url(${MEDIA_PRESETS[p.k]})` }}
            onClick={() => onChange({ ...value, preset: p.k, url: MEDIA_PRESETS[p.k] })}
            title={p.label}
          />
        ))}
      </div>
    </div>
  );
}

function TextEditor({ state, set }) {
  return (
    <>
      <Field label="訊息內容 / Message body" hint="最多 1300 字">
        <textarea
          className="textarea"
          value={state.text}
          onChange={(e) => set({ text: e.target.value })}
          placeholder="嗨 {{name}}，您專屬的 88 折優惠碼是 {{code}}，現在使用一鍵跳轉購物車 →"
          maxLength={1400}
        />
        <Counter value={state.text} max={1300} />
        <VarChips onInsert={(t) => set({ text: (state.text || "") + t })} />
      </Field>
    </>
  );
}

function RichCardEditor({ card, onChange }) {
  return (
    <>
      <Field label="卡片標題 / Card title" hint="最多 200 字">
        <input className="input" value={card.title}
               onChange={(e) => onChange({ ...card, title: e.target.value })}
               placeholder="春季限定 88 折優惠" maxLength={200} />
      </Field>
      <Field label="卡片描述 / Card description" hint="最多 2000 字">
        <textarea className="textarea" value={card.desc}
                  onChange={(e) => onChange({ ...card, desc: e.target.value })}
                  placeholder="嗨 {{name}}，全店任選兩件再享 88 折，活動限 4/30 前。一鍵領取，到 9/30 都能使用。" />
      </Field>
      <Field label="卡片圖片 / Card media">
        <MediaPicker value={{ preset: card.mediaPreset }}
                     onChange={(v) => onChange({ ...card, mediaPreset: v.preset })} />
      </Field>
      <Field label="圖片高度 / Media height">
        <div style={{ display: "flex", gap: 6 }}>
          {[
            { id: "short", label: "矮 168px" },
            { id: "", label: "標準 256px" },
            { id: "tall", label: "高 344px" },
          ].map((m) => (
            <button key={m.id}
              className={"btn btn-sm " + ((card.mediaHeight || "") === m.id ? "btn-primary" : "btn-outline")}
              onClick={() => onChange({ ...card, mediaHeight: m.id })}>
              {m.label}
            </button>
          ))}
        </div>
      </Field>
      <div style={{ marginTop: 8 }}>
        <ActionsEditor
          items={card.actions || []}
          onChange={(items) => onChange({ ...card, actions: items })}
          title="卡片動作按鈕 / Card actions"
          desc="顯示在卡片底部，每張卡片最多 4 個"
        />
      </div>
    </>
  );
}

function CarouselEditor({ cards, onChange }) {
  const [active, setActive] = React.useState(0);
  const addCard = () => {
    if (cards.length >= 10) return;
    const next = [...cards, {
      title: `卡片 ${cards.length + 1}`,
      desc: "簡短描述能讓使用者快速理解這張卡片的訴求。",
      mediaPreset: ["ramen", "shoes", "watch", "coffee", "headphones"][cards.length % 5],
      actions: [{ type: "url", label: "查看詳情", target: "https://" }],
    }];
    onChange(next);
    setActive(next.length - 1);
  };
  const removeCard = (i) => {
    if (cards.length <= 2) return;
    const next = cards.filter((_, idx) => idx !== i);
    onChange(next);
    setActive(Math.min(active, next.length - 1));
  };
  const updateCard = (i, v) => {
    const next = [...cards]; next[i] = v; onChange(next);
  };
  return (
    <div className="carousel-cards">
      <div style={{ display: "flex", gap: 6, overflowX: "auto", paddingBottom: 4, marginBottom: 8 }}>
        {cards.map((c, i) => (
          <button
            key={i}
            onClick={() => setActive(i)}
            className={"btn btn-sm " + (active === i ? "btn-primary" : "btn-outline")}
            style={{ flexShrink: 0 }}
          >
            卡片 {i + 1}
          </button>
        ))}
        <button className="btn btn-sm btn-ghost" onClick={addCard} disabled={cards.length >= 10}>
          <I.Plus size={12} /> 新增卡片
        </button>
      </div>
      <div className="cc-card active">
        <div className="cc-head">
          <div className="cc-num">{active + 1}</div>
          <h6>編輯卡片 #{active + 1}</h6>
          <div className="actions">
            <button title="複製" onClick={() => {
              const next = [...cards];
              next.splice(active + 1, 0, { ...cards[active] });
              onChange(next);
              setActive(active + 1);
            }}><I.Copy size={13} /></button>
            <button title="刪除" disabled={cards.length <= 2} onClick={() => removeCard(active)}>
              <I.Trash size={13} />
            </button>
          </div>
        </div>
        <RichCardEditor card={cards[active]} onChange={(v) => updateCard(active, v)} />
      </div>
      <div style={{ fontSize: 11, color: "var(--rh-fg-muted)", marginTop: 4 }}>
        共 {cards.length} 張卡片 · RCS 規範 2-10 張之間 · 卡片寬度建議 256–304px
      </div>
    </div>
  );
}

function MediaEditor({ media, onChange }) {
  return (
    <>
      <Field label="媒體類型 / Media type">
        <div style={{ display: "flex", gap: 6 }}>
          {["image", "video"].map((k) => (
            <button key={k}
              className={"btn btn-sm " + (media.kind === k ? "btn-primary" : "btn-outline")}
              onClick={() => onChange({ ...media, kind: k })}>
              {k === "image" ? "🖼  圖片" : "▶  影片"}
            </button>
          ))}
        </div>
      </Field>
      <Field label="選擇媒體 / Pick media">
        <MediaPicker value={{ preset: media.preset }} onChange={(v) => onChange({ ...media, ...v })} allowVideo />
      </Field>
      <Field label="附加文字 / Caption (選填)">
        <input className="input" value={media.caption}
               onChange={(e) => onChange({ ...media, caption: e.target.value })}
               placeholder="新品上市 — 點圖看詳細介紹" />
      </Field>
    </>
  );
}

window.MESSAGE_TYPES = MESSAGE_TYPES;
window.ACTION_TYPES = ACTION_TYPES;
window.ActionsEditor = ActionsEditor;
window.TextEditor = TextEditor;
window.RichCardEditor = RichCardEditor;
window.CarouselEditor = CarouselEditor;
window.MediaEditor = MediaEditor;
window.MediaPicker = MediaPicker;
