/* ============================================================
   PRODUCER CONTROL DOCK
   ============================================================ */
const { useState: useStateC } = React;

function getIn(obj, path) {
  return path.split(".").reduce((o, k) => (o == null ? o : o[k]), obj);
}
function setIn(obj, path, val) {
  const keys = path.split(".");
  const root = Array.isArray(obj) ? [...obj] : { ...obj };
  let cur = root;
  for (let i = 0; i < keys.length - 1; i++) {
    const k = keys[i];
    const nv = Array.isArray(cur[k]) ? [...cur[k]] : { ...cur[k] };
    cur[k] = nv; cur = nv;
  }
  cur[keys[keys.length - 1]] = val;
  return root;
}

function Txt({ label, path, state, setState, full, area, ph }) {
  const val = getIn(state, path) ?? "";
  const onChange = (e) => setState((st) => setIn(st, path, e.target.value));
  return (
    <div className={"field" + (full ? " col-span" : "")}>
      <label>{label}</label>
      {area
        ? <textarea value={val} onChange={onChange} placeholder={ph}></textarea>
        : <input value={val} onChange={onChange} placeholder={ph} />}
    </div>
  );
}

const THEMES = [
  { id: "apex",  name: "Apex",  desc: "Brand red · angled frosted glass", sw: ["#E51D24", "#2C66DE", "#0b0d12"] },
  { id: "grid",  name: "Grid",  desc: "NASCAR-style bold solid blocks",   sw: ["#E10600", "#2C66DE", "#07080b"] },
  { id: "slate", name: "Slate", desc: "Minimal hairline · warm accent",   sw: ["#FF6A2C", "#0d0f14", "#AEB6C4"] },
];

const SECTIONS = [
  ["bug", "Event Bug"], ["run", "Run Telemetry"], ["standings", "Standings"],
  ["lower", "Lower Third"], ["upnext", "Up Next"], ["ticker", "Ticker"],
  ["sponsor", "Sponsors"], ["matchup", "Drag Matchup"], ["intermission", "Intermission"],
];

function Dock({ state, setState, open, setOpen, onSimulate }) {
  const [tab, setTab] = useStateC("air");
  const v = state.visible;
  const toggle = (k) => setState((st) => setIn(st, "visible." + k, !st.visible[k]));

  return (
    <div className={"dock" + (open ? " open" : "")}>
      <div className="dock-top">
        <div className="dock-title"><i></i>Producer Control</div>
        <div className="dock-tabs">
          {[["air", "Air & Look"], ["talent", "Talent / Run"], ["matchup", "Matchup"], ["standings", "Standings"], ["ticker", "Ticker & Cards"]].map(([id, lab]) => (
            <button key={id} className={"dock-tab" + (tab === id ? " active" : "")} onClick={() => setTab(id)}>{lab}</button>
          ))}
        </div>
        <button className="dock-close" onClick={() => setOpen(false)}>×</button>
      </div>

      <div className="dock-body">
        {tab === "air" && (
          <div style={{ display: "grid", gap: 22 }}>
            <div>
              <div className="dock-section-title">On-Air Sections</div>
              <div className="toggle-row">
                {SECTIONS.map(([k, lab]) => (
                  <div key={k} className={"tgl" + (v[k] ? " on" : "")} onClick={() => toggle(k)}>
                    <span>{lab}</span><div className="sw"></div>
                  </div>
                ))}
              </div>
            </div>
            <div>
              <div className="dock-section-title">Discipline</div>
              <div className="row-flex">
                <div className="seg">
                  {[["dyno", "Dyno"], ["drag", "Drag"], ["pull", "Sled Pull"]].map(([id, lab]) => (
                    <button key={id} className={state.discipline === id ? "on" : ""}
                      onClick={() => setState((st) => setIn(st, "discipline", id))}>{lab}</button>
                  ))}
                </div>
                <div className="spacer"></div>
                <button className="btn-primary" onClick={onSimulate}>▶ Simulate Live Run</button>
              </div>
            </div>
            <div>
              <div className="dock-section-title">Look</div>
              <div className="theme-cards">
                {THEMES.map((t) => (
                  <button key={t.id} className={"theme-card" + (state.theme === t.id ? " on" : "")}
                    onClick={() => setState((st) => setIn(st, "theme", t.id))}>
                    <div className="tc-name">{t.name}</div>
                    <div className="tc-desc">{t.desc}</div>
                    <div className="tc-swatch">{t.sw.map((c, i) => <i key={i} style={{ background: c }}></i>)}</div>
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}

        {tab === "talent" && (
          <div style={{ display: "grid", gap: 22 }}>
            <div>
              <div className="dock-section-title">Lower Third</div>
              <div className="grid4">
                <Txt label="Tag" path="lower.tag" {...{ state, setState }} />
                <Txt label="Car #" path="lower.car" {...{ state, setState }} />
                <Txt label="Driver Name" path="lower.name" {...{ state, setState }} />
                <Txt label="Shop / Team" path="lower.shop" {...{ state, setState }} />
                <Txt label="Truck" path="lower.truck" {...{ state, setState }} />
                <Txt label="Hometown" path="lower.home" {...{ state, setState }} />
              </div>
            </div>
            <div>
              <div className="dock-section-title">Run Telemetry — {state.discipline}</div>
              <div className="grid4">
                <Txt label="Round / Class" path="run.round" {...{ state, setState }} full />
                <Txt label="Driver" path="run.name" {...{ state, setState }} />
                <Txt label="Car #" path="run.car" {...{ state, setState }} />
                <Txt label="Shop" path="run.shop" {...{ state, setState }} />
                <div></div>
                {state.discipline === "dyno" && <>
                  <Txt label="Peak HP" path="run.hp" {...{ state, setState }} />
                  <Txt label="Peak Torque" path="run.tq" {...{ state, setState }} />
                  <Txt label="Boost (psi)" path="run.boost" {...{ state, setState }} />
                </>}
                {state.discipline === "drag" && <>
                  <Txt label="ET (sec)" path="run.et" {...{ state, setState }} />
                  <Txt label="Trap (mph)" path="run.mph" {...{ state, setState }} />
                  <Txt label="Reaction" path="run.rt" {...{ state, setState }} />
                </>}
                {state.discipline === "pull" && <>
                  <Txt label="Distance (ft)" path="run.dist" {...{ state, setState }} />
                  <Txt label="Class (lb)" path="run.weight" {...{ state, setState }} />
                  <Txt label="Result" path="run.hook" {...{ state, setState }} />
                </>}
              </div>
            </div>
            <div>
              <div className="dock-section-title">Up Next</div>
              <div className="grid4">
                <Txt label="Label" path="upnext.label" {...{ state, setState }} />
                <Txt label="Driver Name" path="upnext.name" {...{ state, setState }} />
                <Txt label="Car #" path="upnext.car" {...{ state, setState }} />
              </div>
            </div>
          </div>
        )}

        {tab === "matchup" && (
          <div style={{ display: "grid", gap: 22 }}>
            <div>
              <div className="dock-section-title">Class &amp; Status</div>
              <div className="grid4">
                <Txt label="Class / Index" path="matchup.klass" {...{ state, setState }} />
                <Txt label="Round" path="matchup.round" {...{ state, setState }} />
                <Txt label="Tag" path="matchup.tag" {...{ state, setState }} />
                <div className="field" style={{ justifyContent: "end" }}>
                  <button className="btn-ghost" onClick={() => setState((st) => {
                    const m = st.matchup; return setIn(st, "matchup", { ...m, left: m.right, right: m.left });
                  })}>⇄ Swap Lanes</button>
                </div>
              </div>
            </div>
            <div>
              <div className="dock-section-title" style={{ color: "#E51D24" }}>● Left Lane</div>
              <div className="grid4">
                <Txt label="Car / Entry #" path="matchup.left.car" {...{ state, setState }} />
                <Txt label="Driver Name" path="matchup.left.name" {...{ state, setState }} />
                <Txt label="Hometown" path="matchup.left.home" {...{ state, setState }} />
                <Txt label="Truck" path="matchup.left.truck" {...{ state, setState }} />
                <Txt label="Dial-In / ET" path="matchup.left.dial" {...{ state, setState }} />
              </div>
            </div>
            <div>
              <div className="dock-section-title" style={{ color: "#2C66DE" }}>● Right Lane</div>
              <div className="grid4">
                <Txt label="Car / Entry #" path="matchup.right.car" {...{ state, setState }} />
                <Txt label="Driver Name" path="matchup.right.name" {...{ state, setState }} />
                <Txt label="Hometown" path="matchup.right.home" {...{ state, setState }} />
                <Txt label="Truck" path="matchup.right.truck" {...{ state, setState }} />
                <Txt label="Dial-In / ET" path="matchup.right.dial" {...{ state, setState }} />
              </div>
            </div>
            <div>
              <div className="dock-section-title">Up Next Strip</div>
              <div className="grid4">
                <Txt label="Next Class / Index" path="matchup.next.klass" {...{ state, setState }} />
                <Txt label="Strip Tag" path="matchup.tag" {...{ state, setState }} />
                <Txt label="Left #" path="matchup.next.left.car" {...{ state, setState }} />
                <Txt label="Left Driver" path="matchup.next.left.name" {...{ state, setState }} />
                <Txt label="Right #" path="matchup.next.right.car" {...{ state, setState }} />
                <Txt label="Right Driver" path="matchup.next.right.name" {...{ state, setState }} />
              </div>
            </div>
            <div className="hint">The matchup bar shares the bottom zone with the single Lower Third &amp; Up Next — toggle those off (Air &amp; Look) when the head-to-head is live.</div>
          </div>
        )}

        {tab === "standings" && (
          <div>
            <div className="dock-section-title">Standings</div>
            <div className="grid3" style={{ marginBottom: 16 }}>
              <Txt label="Title" path="standings.title" {...{ state, setState }} />
              <Txt label="Sub / Status" path="standings.meta" {...{ state, setState }} />
              <div className="field">
                <label>Highlight Row</label>
                <select value={state.standings.highlight}
                  onChange={(e) => setState((st) => setIn(st, "standings.highlight", parseInt(e.target.value)))}>
                  <option value={-1}>None</option>
                  {state.standings.rows.map((r, i) => <option key={i} value={i}>{i + 1}. {r.name}</option>)}
                </select>
              </div>
            </div>
            <table className="stand-edit">
              <thead><tr><th></th><th>Car</th><th>Driver</th><th>Shop / Team</th><th>Points</th><th>Trend</th></tr></thead>
              <tbody>
                {state.standings.rows.map((r, i) => (
                  <tr key={i}>
                    <td className="pcell">{i + 1}</td>
                    <td style={{ width: 70 }}><input className="c" value={r.car} onChange={(e) => setState((st) => setIn(st, `standings.rows.${i}.car`, e.target.value))} /></td>
                    <td><input value={r.name} onChange={(e) => setState((st) => setIn(st, `standings.rows.${i}.name`, e.target.value))} /></td>
                    <td><input value={r.shop} onChange={(e) => setState((st) => setIn(st, `standings.rows.${i}.shop`, e.target.value))} /></td>
                    <td style={{ width: 100 }}><input className="c" value={r.pts} onChange={(e) => setState((st) => setIn(st, `standings.rows.${i}.pts`, e.target.value))} /></td>
                    <td style={{ width: 92 }}>
                      <select value={r.d} onChange={(e) => setState((st) => setIn(st, `standings.rows.${i}.d`, e.target.value))}
                        style={{ width: "100%", background: "#14171e", border: "1px solid rgba(255,255,255,.1)", borderRadius: 6, color: "#fff", padding: "6px", fontFamily: "Saira", fontWeight: 600 }}>
                        <option value="up">▲ Up</option><option value="dn">▼ Down</option><option value="same">— Even</option>
                      </select>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {tab === "ticker" && (
          <div style={{ display: "grid", gap: 22 }}>
            <div>
              <div className="dock-section-title">Ticker</div>
              <div className="grid3" style={{ marginBottom: 14 }}>
                <Txt label="Cap Label" path="ticker.label" {...{ state, setState }} />
                <div className="field">
                  <label>Scroll Speed — {state.ticker.speed}</label>
                  <input type="range" min="14" max="80" value={state.ticker.speed}
                    onChange={(e) => setState((st) => setIn(st, "ticker.speed", parseInt(e.target.value)))} />
                </div>
                <Txt label="Sponsor Bar Label" path="sponsor.label" {...{ state, setState }} />
              </div>
              {state.ticker.items.map((it, i) => (
                <div className="grid4" key={i} style={{ marginBottom: 10, alignItems: "end" }}>
                  <Txt label={`Item ${i + 1} — Tag`} path={`ticker.items.${i}.tag`} {...{ state, setState }} />
                  <div className="field" style={{ gridColumn: "span 3" }}>
                    <label>Text</label>
                    <input value={it.text} onChange={(e) => setState((st) => setIn(st, `ticker.items.${i}.text`, e.target.value))} />
                  </div>
                </div>
              ))}
            </div>
            <div>
              <div className="dock-section-title">Intermission / Countdown Card</div>
              <div className="grid4">
                <Txt label="Eyebrow" path="intermission.eyebrow" {...{ state, setState }} />
                <Txt label="Title" path="intermission.title" {...{ state, setState }} full />
                <Txt label="Subtitle" path="intermission.sub" {...{ state, setState }} full />
                <div className="field"><label>Minutes</label><input type="number" value={state.intermission.clockMin}
                  onChange={(e) => setState((st) => setIn(st, "intermission.clockMin", parseInt(e.target.value) || 0))} /></div>
                <div className="field"><label>Seconds</label><input type="number" value={state.intermission.clockSec}
                  onChange={(e) => setState((st) => setIn(st, "intermission.clockSec", parseInt(e.target.value) || 0))} /></div>
                <div className="field" style={{ justifyContent: "end" }}>
                  <button className={"btn-" + (state.visible.intermission ? "primary" : "ghost")}
                    onClick={() => setState((st) => setIn(st, "visible.intermission", !st.visible.intermission))}>
                    {state.visible.intermission ? "● Card Live" : "Show Card"}
                  </button>
                </div>
              </div>
              <div className="hint" style={{ marginTop: 10 }}>Showing the card fades the full-screen intermission over all other graphics — use between rounds.</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

window.Dock = Dock;
