/* global React */
const { useState, useEffect, useRef } = window.ReactHooks;

// Reusable primitives: links, nav, footer, bot, tweaks panel
function useRoute() {
  const get = () => {
    const h = window.location.hash.replace(/^#\/?/, "");
    const [path, query] = h.split("?");
    return { path: path || "home", query: query || "" };
  };
  const [route, setRoute] = useState(get());
  useEffect(() => {
    const on = () => setRoute(get());
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);
  return route;
}

function go(path) {
  window.location.hash = "#/" + path;
}

function Link({ to, className, children, onClick, ...rest }) {
  return (
    <a
      href={"#/" + to}
      className={className}
      onClick={(e) => { onClick && onClick(e); }}
      {...rest}
    >
      {children}
    </a>
  );
}

function Nav({ route }) {
  const is = (p) => (route.path === p || (p === "catalog" && route.path.startsWith("catalog")) || (p === "product" && route.path.startsWith("product")) ? "active" : "");
  return (
    <header className="nav">
      <div className="nav-inner">
        <Link to="home" className="brand" aria-label="TC home">
          <span className="brand-mark">TC</span>
          <span>tcviz</span>
        </Link>
        <nav className="nav-links" aria-label="Primary">
          <Link to="catalog" className={is("catalog") || is("product")}>Catalog</Link>
          <Link to="gallery" className={is("gallery")}>Live gallery</Link>
          <Link to="contact" className={is("contact")}>Support</Link>
          <Link to="admin" className={is("admin")}>Admin</Link>
        </nav>
        <div className="nav-cta">
          <Link to="contact" className="btn btn-ghost btn-sm">Contact sales</Link>
          <Link to="catalog" className="btn btn-sm">Browse visuals</Link>
        </div>
      </div>
    </header>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <Link to="home" className="brand" style={{ marginBottom: 16 }}>
              <span className="brand-mark">TC</span>
              <span>tcviz</span>
            </Link>
            <p className="muted" style={{ maxWidth: 320, marginTop: 16, fontSize: 14 }}>
              Enterprise-grade custom visuals for Power BI. Designed, documented and supported by TC.
            </p>
            <p className="mono" style={{ marginTop: 16, fontSize: 11, letterSpacing: "0.08em", color: "var(--muted)", textTransform: "uppercase" }}>
              Available on Microsoft AppSource
            </p>
          </div>
          <div>
            <h4>Products</h4>
            <ul>
              <li><Link to="catalog">All visuals</Link></li>
              <li><Link to="gallery">Live gallery</Link></li>
              <li><Link to="catalog">Bundles</Link></li>
              <li><Link to="catalog">Release notes</Link></li>
            </ul>
          </div>
          <div>
            <h4>Company</h4>
            <ul>
              <li><Link to="contact">About TC</Link></li>
              <li><Link to="contact">Careers</Link></li>
              <li><Link to="contact">Press</Link></li>
            </ul>
          </div>
          <div>
            <h4>Support</h4>
            <ul>
              <li><Link to="contact">Contact</Link></li>
              <li><a href="mailto:support@tcviz.com">support@tcviz.com</a></li>
              <li><Link to="contact">Documentation</Link></li>
              <li><Link to="contact">Status</Link></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 TC · tcviz.com</span>
          <span>Hosted on Hostinger · All systems operational</span>
        </div>
      </div>
    </footer>
  );
}

function SupportBot() {
  const [open, setOpen] = useState(false);
  const [messages, setMessages] = useState([
    { who: "bot", text: "Hi — I'm the tcviz assistant. This is a preview; a full support bot will go live soon. How can I help?" }
  ]);
  const [input, setInput] = useState("");
  const scrollRef = useRef(null);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, open]);

  const quick = [
    "Installation on Power BI Desktop",
    "Licensing & seats",
    "Compatibility with Fabric",
    "Request a demo"
  ];

  const send = (text) => {
    if (!text || !text.trim()) return;
    const me = { who: "me", text: text.trim() };
    setMessages((m) => [...m, me]);
    setInput("");
    setTimeout(() => {
      setMessages((m) => [
        ...m,
        {
          who: "bot",
          text: "Thanks — a human from TC will pick this up. In the meantime you can also reach us at support@tcviz.com."
        }
      ]);
    }, 600);
  };

  return (
    <div className="bot">
      {open && (
        <div className="bot-panel" role="dialog" aria-label="TC support">
          <div className="bot-head">
            <div>
              <div className="t">TC Support</div>
              <div className="mono" style={{ fontSize: 10, color: "var(--muted)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
                Preview · replies in under 4h
              </div>
            </div>
            <button className="x" onClick={() => setOpen(false)} aria-label="Close">×</button>
          </div>
          <div className="bot-body" ref={scrollRef}>
            {messages.map((m, i) => (
              <div key={i} className={"bot-msg " + (m.who === "me" ? "me" : "")}>{m.text}</div>
            ))}
            <div className="bot-quick">
              {quick.map((q) => (
                <button key={q} onClick={() => send(q)}>{q}</button>
              ))}
            </div>
          </div>
          <div className="bot-foot">
            <input
              value={input}
              placeholder="Type your question…"
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && send(input)}
            />
            <span className="note">ENTER</span>
          </div>
        </div>
      )}
      <button className="bot-button" onClick={() => setOpen((v) => !v)} aria-label="Open TC support">
        <span className="dot" />
        <span>{open ? "Close support" : "Ask TC"}</span>
      </button>
    </div>
  );
}

function TweaksPanel({ tweaks, setTweak }) {
  const accents = [
    ["#2B5CFF", "Cobalt"],
    ["#0A0A0A", "Ink"],
    ["#D95E2A", "Persimmon"],
    ["#1E7A3A", "Pine"],
    ["#7C3AED", "Violet"]
  ];
  return (
    <div className="tweaks" role="complementary" aria-label="Tweaks">
      <div className="th">Tweaks</div>
      <div className="row">
        <label>Accent</label>
        <div className="swatches">
          {accents.map(([c, name]) => (
            <button
              key={c}
              className={"swatch " + (tweaks.accent === c ? "on" : "")}
              style={{ background: c }}
              title={name}
              onClick={() => setTweak("accent", c)}
              aria-label={"Accent " + name}
            />
          ))}
        </div>
      </div>
      <div className="row">
        <label>Theme</label>
        <div className="segment">
          <button className={tweaks.theme === "light" ? "on" : ""} onClick={() => setTweak("theme", "light")}>Light</button>
          <button className={tweaks.theme === "dark" ? "on" : ""} onClick={() => setTweak("theme", "dark")}>Dark</button>
        </div>
      </div>
      <div className="row">
        <label>Density</label>
        <div className="segment">
          <button className={tweaks.density === "comfortable" ? "on" : ""} onClick={() => setTweak("density", "comfortable")}>Comfortable</button>
          <button className={tweaks.density === "compact" ? "on" : ""} onClick={() => setTweak("density", "compact")}>Compact</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { useRoute, go, Link, Nav, Footer, SupportBot, TweaksPanel });
