/* sections-c.jsx — Testimonials, Clients, Contact, Footer */

function Stars({ n }) {
  return <span className="tst-stars">{"★".repeat(n)}{"☆".repeat(5 - n)}</span>;
}

function Testimonials({ auto }) {
  const list = window.TESTIMONIALS;
  const loop = [...list, ...list];
  return (
    <section id="testimonials" className="section">
      <div className="wrap">
        <div className="tst-head-row">
          <SectionHead prompt="git log --reviews --oneline" title="What clients" dim="say" />
          <div className="sec-prompt reveal" style={{ marginBottom: 56 }}><span className="dollar">→</span>&nbsp;{list.length} verified Upwork reviews</div>
        </div>
      </div>
      <div className="tst-track reveal">
        <div className="tst-marquee" style={{ animationPlayState: auto ? "running" : "paused" }}>
          {loop.map((t, i) => (
            <figure className="tst" key={i}>
              <div className="tst-top">
                <div className="tst-mono">{t.img && <img src={t.img} alt={t.n} loading="lazy" onError={(e) => { e.target.style.display = "none"; }} />}{t.co}</div>
                <div className="tst-who"><div className="n">{t.n}</div><div className="r">{t.r}</div></div>
                <Stars n={t.stars} />
              </div>
              <blockquote className="tst-quote">"{t.q}"</blockquote>
              <figcaption className="tst-meta"><span>{t.proj}</span><span>{t.date}</span></figcaption>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}

function Clients() {
  const groups = window.CLIENT_GROUPS;
  const [tab, setTab] = React.useState(0);
  return (
    <section id="clients" className="section">
      <div className="wrap">
        <SectionHead prompt="cat clients.json | filter --by=tech" title="Trusted" dim="by" sub="Brands across travel, edtech, SaaS, e-commerce and more." />
        <div className="cl-tabs reveal">
          {groups.map((g, i) => (
            <button key={g.label} className={"cl-tab" + (i === tab ? " on" : "")} onClick={() => setTab(i)}>
              {g.label} <span style={{ opacity: .6 }}>({g.items.length})</span>
            </button>
          ))}
        </div>
        <div className="cl-grid" key={tab}>
          {groups[tab].items.map(([name, file, url], i) => (
            <a className="cl-card" key={name + i} href={url} target="_blank" rel="noopener" title={name}>
              <span className="arr">↗</span>
              <img src={"assets/images/client/" + file} alt={name} loading="lazy" />
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

function Contact() {
  const [errs, setErrs] = React.useState({});
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const [errMsg, setErrMsg] = React.useState("");
  const submit = async (e) => {
    e.preventDefault();
    const f = e.target;
    const next = {};
    if (!f["name"].value.trim()) next.name = "required";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(f["email"].value)) next.email = "valid email required";
    if (!f["subject"].value.trim()) next.subject = "required";
    if (!f["message"].value.trim()) next.message = "required";
    setErrs(next);
    if (Object.keys(next).length > 0) return;

    const payload = {
      name: f["name"].value.trim(),
      phone: f["phone"].value.trim(),
      email: f["email"].value.trim(),
      subject: f["subject"].value.trim(),
      message: f["message"].value.trim(),
      company: f["company"].value, // honeypot
    };
    setStatus("sending");
    setErrMsg("");
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) {
        let d = ""; try { d = (await res.json()).error || ""; } catch (_) {}
        throw new Error(d || ("Request failed (" + res.status + ")"));
      }
      setStatus("sent");
      f.reset();
      setTimeout(() => setStatus("idle"), 6000);
    } catch (err) {
      setErrMsg(err.message || "Could not send — please email me directly.");
      setStatus("error");
    }
  };
  const fld = (id, label, type, full, req) => (
    <div className={"fld" + (full ? " full" : "") + (errs[id] ? " err" : "")}>
      <label htmlFor={id}>{label} {req && <span className="req">*</span>}</label>
      {type === "textarea"
        ? <textarea id={id} name={id} rows="5"></textarea>
        : <input id={id} name={id} type={type} />}
      {errs[id] && <span className="msg">↳ {errs[id]}</span>}
    </div>
  );
  return (
    <section id="contacts" className="section">
      <div className="wrap">
        <SectionHead prompt="./connect.sh --start-a-project" title="Let's" dim="build" sub="Available for freelance work — start a conversation below or reach out on Upwork." />
        <div className="ct reveal">
          <div className="ct-card">
            <div className="ct-id">
              <div className="mono-av">HW</div>
              <div><div className="n">Haggai Wambua</div><div className="r">Founder · Macvian AI</div></div>
            </div>
            <p>I'm available for freelance work. Connect with me on Upwork or send a message — I reply fast.</p>
            <div className="ct-lines">
              <div className="row"><span className="k">remote</span> Worldwide · async-friendly</div>
              <div className="row"><span className="k">agency</span> <a href="https://macvian.com" target="_blank" rel="noopener">macvian.com ↗</a></div>
              <div className="row"><span className="k">github</span> <a href="https://github.com/haggaiwambua" target="_blank" rel="noopener">github.com/haggaiwambua ↗</a></div>
              <div className="row"><span className="k">status</span> open to new projects</div>
            </div>
            <div className="ct-cta">
              <a className="btn btn-fill" href="https://tinyurl.com/2p9n2h5p" target="_blank" rel="noopener">Hire me on Upwork <Icon name="arrowRight" /></a>
              <a className="btn" href="https://macvian.com" target="_blank" rel="noopener">Hire Macvian AI</a>
            </div>
          </div>
          <div className="ct-form">
            <div className="form-bar"><i></i><i></i><i></i><span style={{ marginLeft: 6 }}>new-message.txt</span></div>
            <form onSubmit={submit} noValidate>
              {fld("name", "Your name", "text", false, true)}
              {fld("phone", "Phone (optional)", "text", false, false)}
              {fld("email", "Email", "email", true, true)}
              {fld("subject", "Subject", "text", true, true)}
              {fld("message", "Message", "textarea", true, true)}
              <input type="text" name="company" tabIndex="-1" autoComplete="off" aria-hidden="true" style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
              <div className="ct-submit">
                <button className="btn btn-fill" type="submit" disabled={status === "sending"}>
                  {status === "sending" ? "Sending…" : <React.Fragment>Send message <Icon name="send" /></React.Fragment>}
                </button>
                <span className={"ct-sent" + (status === "sent" ? " show" : "")}><Icon name="check" style={{ width: 15, height: 15 }} /> message sent — talk soon!</span>
                {status === "error" && <span className="ct-err">↳ {errMsg}</span>}
              </div>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="wrap row">
        <div className="brand">haggai<span className="acc">.dev</span></div>
        <div className="cp">© {new Date().getFullYear()} Haggai Wambua · built in the terminal</div>
        <div className="socials">
          <a href="https://macvian.com" target="_blank" rel="noopener" aria-label="Macvian AI" title="macvian.com"><Icon name="ext" /></a>
          <a href="https://github.com/haggaiwambua" target="_blank" rel="noopener" aria-label="GitHub"><Icon name="github" /></a>
          <a href="https://tinyurl.com/2p9n2h5p" target="_blank" rel="noopener" aria-label="Upwork"><Icon name="briefcase" /></a>
          <a href="#contacts" aria-label="Email"><Icon name="mail" /></a>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Testimonials, Clients, Contact, Footer });
