/* console.jsx — fixed bottom console. Stays put while the world zooms.
 *   • LEFT  : WINDOWS tray — lists every station + open/hidden state, with
 *             show/hide. The only way to bring a closed station back.
 *   • CENTER: a charming dial that switches the background theme.
 *   • RIGHT : an honest status line that opens Talk to Cleo, + account.
 * No operator telemetry — this is the public front door, not a cockpit.
 */
const { useState: useCState } = React;

// The dial cycles these moods. NO COLOR = the background photo with no tint.
// CUSTOM is a separate button (below), not a dial stop — it swaps in your own
// image, and snaps the dial to NO COLOR so nothing is laid over your picture.
const DIAL_THEMES = [
  { id: "nebula",  name: "NEBULA",   color: "#b18cff" },
  { id: "amber",   name: "AMBER",    color: "#ffc850" },
  { id: "green",   name: "GREEN",    color: "#8fd4a3" },
  { id: "dark",    name: "VOID",     color: "#6a7299" },
  { id: "nocolor", name: "NO COLOR", color: "#cfd6e6" },
];

function BottomConsole({ windows, onShow, onHide, theme, onTheme, customImg, onCustomUpload, onClearImage, account, onSignIn, onSignOut, onOpenCleo }) {
  const [trayOpen, setTrayOpen] = useCState(false);
  const fileRef = React.useRef(null);
  const hasCustom = !!customImg;
  const dialIdx = Math.max(0, DIAL_THEMES.findIndex((t) => t.id === theme));
  const active = DIAL_THEMES.find((t) => t.id === theme) || DIAL_THEMES[0];
  const angle = -50 + dialIdx * (100 / (DIAL_THEMES.length - 1));
  const openCount = windows.filter((w) => w.state === "open").length;

  const cycle = () => onTheme(DIAL_THEMES[((dialIdx + 1) % DIAL_THEMES.length)].id);
  const openPicker = () => fileRef.current && fileRef.current.click();
  const pickFile = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    const rd = new FileReader();
    rd.onload = () => onCustomUpload && onCustomUpload(rd.result);
    rd.readAsDataURL(f);
    e.target.value = "";
  };

  return (
    <div className="console" role="region" aria-label="Console">
      {["tl", "tr", "bl", "br"].map((p) => <span key={p} className={`console__rivet console__rivet--${p}`}/>)}
      <div className="console__bezel" aria-hidden="true"/>

      {/* LEFT — windows tray */}
      <div className="console__left">
        <button className="tray-btn" onClick={() => setTrayOpen((o) => !o)} aria-expanded={trayOpen}>
          <span className="tray-btn__icon"><i/><i/><i/><i/></span>
          <span className="col" style={{ alignItems: "flex-start", gap: 1 }}>
            <span className="tray-btn__label">WINDOWS</span>
            <span className="tray-btn__count">{openCount} of {windows.length} open · click to manage</span>
          </span>
        </button>
        {trayOpen && (
          <div className="tray nopan allow-scroll" onMouseDown={(e) => e.stopPropagation()}>
            <div className="tray__head">
              <span className="tray__title">STATIONS</span>
              <button className="iconbtn" onClick={() => setTrayOpen(false)} aria-label="Close tray">
                <svg width="13" height="13" viewBox="0 0 14 14"><path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
              </button>
            </div>
            <div className="tray__list">
              {windows.map((w) => (
                <div key={w.id} className={`tray__row tray__row--${w.state}`}>
                  <span className="tray__dot" style={{ background: w.accent }}/>
                  <span className="tray__name">{w.title}</span>
                  {w.state === "open"
                    ? <button className="tray__toggle" onClick={() => onHide(w.id)}>hide</button>
                    : <button className="tray__toggle is-show" onClick={() => onShow(w.id)}>show</button>}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* CENTER — theme dial + custom background selector */}
      <div className="console__center">
        <button className="dial" onClick={cycle} title="Switch background color" data-theme={active.id}>
          <span className="dial__plate"/>
          <span className="dial__ring"/>
          <span className="dial__notches">
            {Array.from({ length: 12 }).map((_, i) => <span key={i} className="dial__notch" style={{ transform: `rotate(${i * 30}deg) translateY(-30px)` }}/>)}
          </span>
          <span className="dial__face" style={{ boxShadow: `0 0 28px ${active.color}55, inset 0 0 20px ${active.color}33` }}/>
          <span className="dial__needle" style={{ transform: `rotate(${angle}deg)`, background: `linear-gradient(180deg,#fff,${active.color})`, boxShadow: `0 0 12px ${active.color}` }}/>
          <span className="dial__hub"/>
        </button>
        <div className="console__readout">
          <span className="console__readout-label">BACKGROUND</span>
          <span className="console__readout-value" style={{ color: active.color }}>{hasCustom ? "CUSTOM" : active.name}</span>
          <span className="console__readout-sub">{hasCustom ? "your image · clear to remove" : "click the dial to change"}</span>
        </div>
        <button className={"console__custom-btn" + (hasCustom ? " is-on" : "")} onClick={openPicker}
                title={hasCustom ? "Your custom background — click to replace" : "Upload your own background"}>
          <svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3"><rect x="1.5" y="2.5" width="13" height="11" rx="1.6"/><circle cx="5.5" cy="6" r="1.3"/><path d="M2 11.5 6 8l2.5 2L11 7.5l3 3.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
          <span className="console__custom-label">CUSTOM</span>
        </button>
        {hasCustom && (
          <button className="console__clear-btn" onClick={onClearImage} title="Remove your custom background — back to the cosmos">
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 3l8 8M11 3l-8 8" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
            <span className="console__custom-label">CLEAR</span>
          </button>
        )}
        <input ref={fileRef} type="file" accept="image/*" onChange={pickFile} style={{ display: "none" }}/>
      </div>

      {/* RIGHT — sign in (bigger) + status line */}
      <div className="console__right">
        {account
          ? (
            <div className="console__acct">
              <span className="console__acct-who">@{account.handle}</span>
              <button className="linkbtn" onClick={onSignOut}>sign out</button>
            </div>
          )
          : (
            <button className="console__signin" onClick={onSignIn}>
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="8" cy="5.5" r="2.6"/><path d="M3 13.5c0-2.5 2.2-4 5-4s5 1.5 5 4" strokeLinecap="round"/></svg>
              <span>Sign in</span>
            </button>
          )}
        <button className="status-line" onClick={onOpenCleo} title="Open Talk to Cleo">
          <span className="status-line__pulse"/>
          <span className="col" style={{ alignItems: "flex-start", gap: 1 }}>
            <span className="status-line__main">ready when you are</span>
            <span className="status-line__sub">say hello to Cleo →</span>
          </span>
        </button>
      </div>

      <div className="console__plate-name">NATE BUILDS AI</div>
    </div>
  );
}

window.BottomConsole = BottomConsole;
