// Tweak panel — lets the booth operator edit questions, choices, and images
// without touching code. Posts back to the host so edits persist.
//
// `data.questions` is a list of pools; each pool has alternative variants.
// Tabs flatten to "Q{slot}-{A|B|...}" so every variant is editable.

function TweakPanel({ data, onChange, onClose }) {
  // Flat list of (slot, variant) pairs derived from pools.
  // Pools are ordered by difficulty level (Lv.1, Lv.2, Lv.3...).
  const tabs = React.useMemo(() => {
    const out = [];
    data.questions.forEach((pool, slot) => {
      pool.forEach((_, variant) => {
        const letter = String.fromCharCode(65 + variant);
        out.push({ slot, variant, label: `Lv.${slot + 1}-${letter}` });
      });
    });
    return out;
  }, [data.questions]);

  const [tab, setTab] = React.useState(0);
  const [localData, setLocalData] = React.useState(data);

  React.useEffect(() => setLocalData(data), [data]);

  const push = (next) => {
    setLocalData(next);
    onChange(next);
  };

  const updateQuestion = (slot, variant, patch) => {
    const next = structuredClone(localData);
    Object.assign(next.questions[slot][variant], patch);
    push(next);
  };
  const updateChoice = (slot, variant, ci, patch) => {
    const next = structuredClone(localData);
    Object.assign(next.questions[slot][variant].choices[ci], patch);
    if (patch.correct) {
      next.questions[slot][variant].choices.forEach((c, idx) => {
        c.correct = idx === ci;
      });
    }
    push(next);
  };
  const setChoiceCount = (slot, variant, count) => {
    const next = structuredClone(localData);
    const cur = next.questions[slot][variant].choices;
    while (cur.length < count) cur.push({ label: "新しい選択肢", correct: false });
    while (cur.length > count) cur.pop();
    if (!cur.some((c) => c.correct)) cur[0].correct = true;
    push(next);
  };

  const handleImageUpload = (slot, variant, file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      updateQuestion(slot, variant, { image: reader.result });
    };
    reader.readAsDataURL(file);
  };

  const isMeta = tab === "meta";
  const tabInfo = isMeta ? null : tabs[Math.min(tab, tabs.length - 1)];
  const q = tabInfo ? localData.questions[tabInfo.slot][tabInfo.variant] : null;

  return (
    <div className="dk-tweak-panel">
      <div className="dk-tweak-head">
        <div className="dk-tweak-title">
          <span className="dk-tweak-dot" />
          Tweaks
        </div>
        <button className="dk-tweak-close" onClick={onClose} aria-label="close">
          ✕
        </button>
      </div>

      {/* Tabs: one per (slot × variant) plus a meta tab */}
      <div className="dk-tweak-tabs">
        {tabs.map((t, i) => (
          <button
            key={`${t.slot}-${t.variant}`}
            className={`dk-tweak-tab ${tab === i ? "dk-tweak-tab-active" : ""}`}
            onClick={() => setTab(i)}
          >
            {t.label}
          </button>
        ))}
        <button
          className={`dk-tweak-tab ${isMeta ? "dk-tweak-tab-active" : ""}`}
          onClick={() => setTab("meta")}
        >
          全般
        </button>
      </div>

      <div className="dk-tweak-body">
        {isMeta ? (
          <MetaEditor data={localData} onChange={push} />
        ) : (
          <>
            <label className="dk-tweak-field">
              <span>見出し</span>
              <input
                type="text"
                value={q.heading}
                onChange={(e) =>
                  updateQuestion(tabInfo.slot, tabInfo.variant, { heading: e.target.value })
                }
              />
            </label>
            <label className="dk-tweak-field">
              <span>問題文</span>
              <textarea
                rows={3}
                value={q.question}
                onChange={(e) =>
                  updateQuestion(tabInfo.slot, tabInfo.variant, { question: e.target.value })
                }
              />
            </label>
            <label className="dk-tweak-field">
              <span>絵文字（画像なし時）</span>
              <input
                type="text"
                value={q.imageEmoji || ""}
                onChange={(e) =>
                  updateQuestion(tabInfo.slot, tabInfo.variant, { imageEmoji: e.target.value })
                }
              />
            </label>

            <div className="dk-tweak-field">
              <span>画像（任意）</span>
              <div className="dk-tweak-imagerow">
                {q.image ? (
                  <div className="dk-tweak-thumb">
                    <img src={q.image} alt="" />
                    <button
                      className="dk-tweak-thumb-remove"
                      onClick={() =>
                        updateQuestion(tabInfo.slot, tabInfo.variant, { image: "" })
                      }
                    >
                      ✕
                    </button>
                  </div>
                ) : (
                  <label className="dk-tweak-upload">
                    <input
                      type="file"
                      accept="image/*"
                      onChange={(e) =>
                        handleImageUpload(tabInfo.slot, tabInfo.variant, e.target.files?.[0])
                      }
                    />
                    <span>＋ 画像をアップロード</span>
                  </label>
                )}
              </div>
            </div>

            <div className="dk-tweak-field">
              <span>選択肢の数</span>
              <div className="dk-tweak-seg">
                {[2, 3, 4].map((n) => (
                  <button
                    key={n}
                    className={`dk-tweak-segbtn ${
                      q.choices.length === n ? "dk-tweak-segbtn-on" : ""
                    }`}
                    onClick={() => setChoiceCount(tabInfo.slot, tabInfo.variant, n)}
                  >
                    {n}択
                  </button>
                ))}
              </div>
            </div>

            {q.choices.map((c, ci) => (
              <div
                key={ci}
                className={`dk-tweak-choice ${c.correct ? "dk-tweak-choice-correct" : ""}`}
              >
                <button
                  className="dk-tweak-correct-toggle"
                  onClick={() =>
                    updateChoice(tabInfo.slot, tabInfo.variant, ci, { correct: true })
                  }
                  aria-label="正解にする"
                >
                  {c.correct ? "◯" : "○"}
                </button>
                <input
                  className="dk-tweak-choice-input"
                  value={c.label}
                  onChange={(e) =>
                    updateChoice(tabInfo.slot, tabInfo.variant, ci, { label: e.target.value })
                  }
                />
              </div>
            ))}

            <label className="dk-tweak-field">
              <span>解説</span>
              <textarea
                rows={3}
                value={q.explanation}
                onChange={(e) =>
                  updateQuestion(tabInfo.slot, tabInfo.variant, { explanation: e.target.value })
                }
              />
            </label>
          </>
        )}
      </div>
    </div>
  );
}

function MetaEditor({ data, onChange }) {
  const set = (patch) => onChange({ ...data, ...patch });
  return (
    <>
      <label className="dk-tweak-field">
        <span>見出し</span>
        <input
          type="text"
          value={data.boothHeadline}
          onChange={(e) => set({ boothHeadline: e.target.value })}
        />
      </label>
      <label className="dk-tweak-field">
        <span>サブ</span>
        <input
          type="text"
          value={data.boothSub}
          onChange={(e) => set({ boothSub: e.target.value })}
        />
      </label>
      <label className="dk-tweak-field">
        <span>イベントタグ</span>
        <input
          type="text"
          value={data.eventTag}
          onChange={(e) => set({ eventTag: e.target.value })}
        />
      </label>
      <label className="dk-tweak-field">
        <span>イベント名</span>
        <input
          type="text"
          value={data.eventName}
          onChange={(e) => set({ eventName: e.target.value })}
        />
      </label>
      <label className="dk-tweak-field">
        <span>Xシェア文言（{"{score}"} で正解数、{"{total}"} で総問題数）</span>
        <textarea
          rows={4}
          value={data.shareTextTemplate}
          onChange={(e) => set({ shareTextTemplate: e.target.value })}
        />
      </label>
      <label className="dk-tweak-field">
        <span>シェアURL</span>
        <input
          type="text"
          value={data.shareUrl}
          onChange={(e) => set({ shareUrl: e.target.value })}
        />
      </label>

    </>
  );
}

window.TweakPanel = TweakPanel;
