// SplitPicker.jsx — split-mode editor reused by Entry & Templates screens
const { useState } = React;

function SplitPicker({ amount, names, value, accent, onChange, onTotalDriven, hideTabs }) {
  // local UI state for ratio mode
  const [ratioMode, setRatioMode] = useState(value.mode === "ratio" && value.custom ? "custom" : "slider");
  const [ratioA, setRatioA] = useState(value.mode === "ratio" ? value.ratio[0] : 5);
  const [ratioB, setRatioB] = useState(value.mode === "ratio" ? value.ratio[1] : 5);
  const [customRA, setCustomRA] = useState(value.mode === "ratio" ? String(value.ratio[0]) : "");
  const [customRB, setCustomRB] = useState(value.mode === "ratio" ? String(value.ratio[1]) : "");

  // local UI state for custom amount mode
  const [amountMode, setAmountMode] = useState(value.mode === "custom" && value.amounts?.totalDriven ? "custom" : "auto");
  const [amtA, setAmtA] = useState(value.mode === "custom" ? String(value.amounts.A) : String(Math.round(amount / 2)));
  const [amtB, setAmtB] = useState(
    value.mode === "custom" ?
    String(value.amounts.B) :
    String(Math.max(0, Math.round((amount - parseFloat(amtA || 0)) * 100) / 100))
  );

  const tabs = [
  { id: "even", label: "均分" },
  { id: "ratio", label: "比例" },
  { id: "custom", label: "金額" },
  { id: "treat", label: "請客" }];


  function pickTab(id) {
    if (id === "even") onChange({ mode: "even" });
    if (id === "ratio") {
      const a = parseFloat(customRA) || ratioA, b = parseFloat(customRB) || ratioB;
      onChange({ mode: "ratio", ratio: [a, b], custom: ratioMode === "custom" });
    }
    if (id === "custom") {
      const a = parseFloat(amtA) || 0, b = parseFloat(amtB) || 0;
      onChange({ mode: "custom", amounts: { A: a, B: b, totalDriven: amountMode === "custom" } });
      if (amountMode === "custom") onTotalDriven(a + b);
    }
    if (id === "treat") onChange({ mode: "treat", treatBy: "A" });
  }

  function onSlider(a) {
    setRatioA(a); setRatioB(10 - a);
    setCustomRA(String(a)); setCustomRB(String(10 - a));
    onChange({ mode: "ratio", ratio: [a, 10 - a], custom: false });
  }
  function onCustomR(which, v) {
    if (which === "A") setCustomRA(v); else setCustomRB(v);
    const a = parseFloat(which === "A" ? v : customRA) || 0;
    const b = parseFloat(which === "B" ? v : customRB) || 0;
    onChange({ mode: "ratio", ratio: [a, b], custom: true });
  }

  function onAmtA(v) {
    setAmtA(v);
    const a = parseFloat(v) || 0;
    if (amountMode === "auto") {
      const b = Math.max(0, Math.round((amount - a) * 100) / 100);
      setAmtB(String(b));
      onChange({ mode: "custom", amounts: { A: a, B: b, totalDriven: false } });
    } else {
      const b = parseFloat(amtB) || 0;
      onChange({ mode: "custom", amounts: { A: a, B: b, totalDriven: true } });
      onTotalDriven(a + b);
    }
  }
  function onAmtB(v) {
    setAmtB(v);
    const a = parseFloat(amtA) || 0;
    const b = parseFloat(v) || 0;
    if (amountMode === "auto") {
      onChange({ mode: "custom", amounts: { A: a, B: b, totalDriven: false } });
    } else {
      onChange({ mode: "custom", amounts: { A: a, B: b, totalDriven: true } });
      onTotalDriven(a + b);
    }
  }

  const autoSum = (parseFloat(amtA) || 0) + (parseFloat(amtB) || 0);

  const ra = parseFloat(customRA) || ratioA;
  const rb = parseFloat(customRB) || ratioB;
  const ratioTotal = ra + rb;

  return (
    <div className="split-pick">
      {!hideTabs &&
      <div className="split-tabs">
        {tabs.map((t) =>
        <button key={t.id}
        className={"split-tab" + (value.mode === t.id ? " is-on" : "")}
        style={value.mode === t.id ? { color: accent, borderBottomColor: accent } : {}}
        onClick={() => pickTab(t.id)}>{t.label}</button>
        )}
      </div>
      }

      {value.mode === "even" &&
      <div className="split-body">
          <div className="split-line"><span>{names.A}</span><span className="num">{fmtMoney(amount / 2)}</span></div>
          <div className="split-line"><span>{names.B}</span><span className="num">{fmtMoney(amount / 2)}</span></div>
        </div>
      }

      {value.mode === "ratio" &&
      <div className="split-body">
          <div className="mode-toggle">
            <button className={"mode-btn" + (ratioMode === "slider" ? " is-on" : "")}
          onClick={() => { setRatioMode("slider"); onChange({ mode: "ratio", ratio: [ratioA, 10 - ratioA], custom: false }); }}>滑桿</button>
            <button className={"mode-btn" + (ratioMode === "custom" ? " is-on" : "")}
          onClick={() => {
            setRatioMode("custom");
            const a = parseFloat(customRA) || ratioA, b = parseFloat(customRB) || ratioB;
            onChange({ mode: "ratio", ratio: [a, b], custom: true });
          }}>自訂</button>
          </div>

          {ratioMode === "slider" ?
        <>
              <div className="split-ratio-display">
                <span style={{ color: accent }}>{ratioA}</span>
                <span>:</span>
                <span style={{ color: accent }}>{10 - ratioA}</span>
              </div>
              <input type="range" min="1" max="9" step="1" value={ratioA}
          onChange={(e) => onSlider(parseInt(e.target.value))}
          className="split-slider" style={{ accentColor: accent }} />
            </> :

        <>
              <div className="split-ratio-inputs">
                <input className="custom-input num" type="number" inputMode="decimal" value={customRA}
            onFocus={selectOnFocus}
            onChange={(e) => onCustomR("A", e.target.value)} />
                <span style={{ fontSize: 24, color: "#888" }}>:</span>
                <input className="custom-input num" type="number" inputMode="decimal" value={customRB}
            onFocus={selectOnFocus}
            onChange={(e) => onCustomR("B", e.target.value)} />
              </div>
              <input type="range" min="1" max="9" step="1" value={ratioA}
          disabled className="split-slider disabled" />
            </>
        }

          <div className="split-line">
            <span>{names.A}</span>
            <span className="num">{ratioTotal > 0 ? fmtMoney(amount * ra / ratioTotal) : 0}</span>
          </div>
          <div className="split-line">
            <span>{names.B}</span>
            <span className="num">{ratioTotal > 0 ? fmtMoney(amount * rb / ratioTotal) : 0}</span>
          </div>
        </div>
      }

      {value.mode === "custom" &&
      <div className="split-body">
          <div className="mode-toggle">
            <button className={"mode-btn" + (amountMode === "auto" ? " is-on" : "")}
          onClick={() => {
            setAmountMode("auto");
            const a = parseFloat(amtA) || 0;
            const b = Math.max(0, Math.round((amount - a) * 100) / 100);
            setAmtB(String(b));
            onChange({ mode: "custom", amounts: { A: a, B: b, totalDriven: false } });
          }}>總額分配</button>
            <button className={"mode-btn" + (amountMode === "custom" ? " is-on" : "")}
          onClick={() => {
            setAmountMode("custom");
            const a = parseFloat(amtA) || 0, b = parseFloat(amtB) || 0;
            onChange({ mode: "custom", amounts: { A: a, B: b, totalDriven: true } });
            onTotalDriven(a + b);
          }}>自訂</button>
          </div>

          <div className="custom-line">
            <span>{names.A}</span>
            <input type="number" inputMode="decimal" value={amtA}
          onFocus={selectOnFocus}
          onChange={(e) => onAmtA(e.target.value)} className="custom-input num" />
          </div>
          <div className="custom-line">
            <span>{names.B}</span>
            {amountMode === "auto" ?
          <span className="custom-input num readonly">{fmtMoney(parseFloat(amtB) || 0)}</span> :

          <input type="number" inputMode="decimal" value={amtB}
          onFocus={selectOnFocus}
          onChange={(e) => onAmtB(e.target.value)} className="custom-input num" />
          }
          </div>
          <div className="split-hint">
            {amountMode === "auto" ?
          `合計需為 NT$ ${fmtMoney(amount)}` :
          `合計 NT$ ${fmtMoney(autoSum)}`}
          </div>
        </div>
      }

      {value.mode === "treat" &&
      <div className="split-body">
          <div className="treat-pick">
            {["A", "B"].map((k) =>
          <button key={k}
          className={"treat-btn" + (value.treatBy === k ? " is-on" : "")}
          style={value.treatBy === k ? { borderColor: accent, color: accent } : {}}
          onClick={() => onChange({ mode: "treat", treatBy: k })}>
                {names[k]} 請客
              </button>
          )}
          </div>
        </div>
      }
    </div>);
}

window.SplitPicker = SplitPicker;
