/* global React */
/* Uses window.ConfigContext exposed by app.jsx */

function useConfig() {
  return React.useContext(window.ConfigContext) || window.SITE_CONFIG;
}

/* ---------- About ---------- */
function AboutPanel() {
  const cfg = useConfig().about;
  return (
    <div className="about-grid">
      <div className="about-portrait">
        <img src={cfg.image} alt="Portrait of Riley at her desk" />
      </div>
      <div className="about-meta">
        <h2 className="about-headline">{cfg.headline}</h2>
        {cfg.bio.map((p, i) => (
          <p key={i} className="bio">{p}</p>
        ))}
        <div className="about-substack">
          <a
            href="https://rileysliving.substack.com/"
            target="_blank"
            rel="noopener noreferrer"
            className="pill-btn is-light about-substack-btn"
            data-cursor="hover"
          >
            ↳ Subscribe to the Substack <span className="arrow">&rarr;</span>
          </a>
        </div>
      </div>
    </div>
  );
}

/* ---------- Work ---------- */
function WorkPanel() {
  const cfg = useConfig().work;
  const [hovered, setHovered] = React.useState(null);
  const onMove = (e) => {};

  return (
    <div className="work-grid" onMouseMove={onMove}>
      {cfg.items.map((w, i) => {
        const hasUrl = w.url && w.url !== "#";
        const Tag = hasUrl ? "a" : "div";
        const linkProps = hasUrl
          ? { href: w.url, target: "_blank", rel: "noopener noreferrer" }
          : {};
        return (
          <Tag
            key={w.n}
            className="work-row"
            data-cursor="hover"
            onMouseEnter={() => setHovered(i)}
            onMouseLeave={() => setHovered(null)}
            {...linkProps}
          >
            <div className="n">{w.n}</div>
            <div className="title">{w.title}</div>
            <div className="meta">{w.kind}</div>
            <div className="meta right">{w.year}</div>
            <div className="arrow">{hasUrl ? "↗" : "→"}</div>
          </Tag>
        );
      })}
    </div>
  );
}

/* ---------- Journal ---------- */
function JournalPanel() {
  const cfg = useConfig().journal;
  return (
    <div className="journal-grid">
      {cfg.items.map((j, i) => (
        <article key={i} className="journal-entry" data-cursor="hover">
          <div className="date">{j.date} · Essay</div>
          <h3 className="head">{j.head}</h3>
          <p className="lede">{j.lede}</p>
        </article>
      ))}
    </div>
  );
}

/* ---------- Selected Work (landing section) ---------- */
function SelectedWork({ onOpen }) {
  const cfg = useConfig().work;
  return (
    <section className="selected" data-screen-label="02 Selected Work">
      <header className="section-header">
        <div className="mono section-eyebrow">{cfg.sectionEyebrow}</div>
        <h2 className="section-title display">{cfg.sectionTitle}</h2>
      </header>
      <div className="work-grid landing-work">
        {cfg.items.slice(0, 5).map((w) => (
          <button key={w.n} className="work-row" data-cursor="hover" onClick={onOpen}>
            <div className="n">{w.n}</div>
            <div className="title">{w.title}</div>
            <div className="meta">{w.kind}</div>
            <div className="meta right">{w.year}</div>
            <div className="arrow">Discover case &rarr;</div>
          </button>
        ))}
      </div>
      <div className="section-foot">
        <button className="pill-btn is-light" onClick={onOpen} data-cursor="hover">
          See all {cfg.items.length} projects <span className="arrow">&rarr;</span>
        </button>
      </div>
    </section>
  );
}

/* ---------- Services ---------- */
function Services() {
  const cfg = useConfig().services;
  return (
    <section className="services" data-screen-label="03 Services">
      <header className="section-header">
        <div className="mono section-eyebrow">{cfg.sectionEyebrow}</div>
        <h2 className="section-title display">{cfg.sectionTitle}</h2>
      </header>
      <div className="service-grid">
        {cfg.items.map((s, i) => (
          <article key={s.n} className="service-card" data-cursor="hover">
            <div className="service-top">
              <span className="mono service-n">{`0${i + 1} / ${s.n}`}</span>
              <span className="mono service-tag">{s.tag}</span>
            </div>
            <h3 className="service-head display">{s.head}</h3>
            <p className="service-focus">{s.focus}</p>
            <ul className="service-outcomes">
              {s.outcomes.map((o) => (
                <li key={o}><span className="bullet">&#9679;</span>{o}</li>
              ))}
            </ul>
            <div className="service-foot">
              <a href={s.ctaHref} className={"pill-btn small" + (s.ctaStyle === "light" ? " is-light" : "")} data-cursor="hover" rel="noopener noreferrer">
                {s.ctaLabel} <span className="arrow">&rarr;</span>
              </a>
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

/* ---------- Testimonials ---------- */
function Testimonials() {
  const cfg = useConfig().testimonials;
  return (
    <section className="testimonials" data-screen-label="04 Testimonials">
      <header className="section-header">
        <div className="mono section-eyebrow">{cfg.sectionEyebrow}</div>
        <h2 className="section-title display">{cfg.sectionTitle}</h2>
      </header>
      <div className="quotes-grid">
        {cfg.items.map((q, i) => (
          <figure key={i} className="quote-card" data-cursor="hover">
            <div className="quote-mark" aria-hidden="true">&ldquo;</div>
            <blockquote className="quote-text">{q.quote}</blockquote>
            <figcaption className="quote-cap">
              <div className="quote-name">{q.name}</div>
              <div className="mono quote-title">{q.title}</div>
            </figcaption>
            <a href="#contact" className="pill-btn small" data-cursor="hover">
              Contact me <span className="arrow">&rarr;</span>
            </a>
          </figure>
        ))}
      </div>
    </section>
  );
}

/* ---------- Contact Form ---------- */
/* Replace YOUR_FORM_ID below with your Formspree ID (formspree.io → New Form) */
const FORMSPREE_ENDPOINT = "https://formspree.io/f/xojbrbnd";

function ContactForm() {
  const [status, setStatus] = React.useState("idle"); /* idle | sending | sent | error */

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus("sending");
    try {
      const res = await fetch(FORMSPREE_ENDPOINT, {
        method: "POST",
        body: new FormData(e.target),
        headers: { "Accept": "application/json" },
      });
      if (res.ok) { setStatus("sent"); e.target.reset(); }
      else { setStatus("error"); }
    } catch { setStatus("error"); }
  };

  if (status === "sent") {
    return (
      <div className="cf-success">
        <span className="cf-success-mark">✺</span>
        <p>Message sent — I&rsquo;ll be in touch soon.</p>
      </div>
    );
  }

  return (
    <form className="cf" onSubmit={handleSubmit} noValidate>
      {/* Honeypot — invisible to humans, bots fill it in; Formspree rejects those submissions */}
      <input type="text" name="_gotcha" style={{ display: "none" }} tabIndex={-1} autoComplete="off" aria-hidden="true" />
      <div className="cf-row">
        <div className="cf-field">
          <label className="mono cf-label" htmlFor="cf-first">First name</label>
          <input className="cf-input" type="text" id="cf-first" name="firstName" required />
        </div>
        <div className="cf-field">
          <label className="mono cf-label" htmlFor="cf-last">Last name</label>
          <input className="cf-input" type="text" id="cf-last" name="lastName" required />
        </div>
      </div>
      <div className="cf-field">
        <label className="mono cf-label" htmlFor="cf-email">Email</label>
        <input className="cf-input" type="email" id="cf-email" name="email" required />
      </div>
      <div className="cf-field">
        <label className="mono cf-label" htmlFor="cf-msg">Message</label>
        <textarea className="cf-input cf-textarea" id="cf-msg" name="message" required rows="4" />
      </div>
      <div className="cf-footer">
        <button
          type="submit"
          className={"pill-btn xl cf-submit" + (status === "sending" ? " cf-sending" : "")}
          disabled={status === "sending"}
          data-cursor="hover"
        >
          {status === "sending" ? "Sending…" : "Send message"} <span className="arrow">→</span>
        </button>
        {status === "error" && (
          <p className="mono cf-error">Something went wrong — please try again.</p>
        )}
      </div>
    </form>
  );
}

/* ---------- Contact ---------- */
function ContactBlock() {
  const cfg = useConfig().contact;
  return (
    <section id="contact" className="contact" data-screen-label="05 Contact">
      <div className="contact-eyebrow mono">{cfg.eyebrow}</div>
      <h2 className="contact-headline display">
        {cfg.headline1} <em>{cfg.headline2}</em>
      </h2>
      <div className="contact-meta contact-meta--single">
        <div className="contact-col">
          <div className="mono contact-label">Location</div>
          <div className="contact-val">{cfg.colLocation}</div>
        </div>
      </div>
      <ContactForm />
    </section>
  );
}

/* ---------- Services Panel (for panel overlay) ---------- */
function ServicesPanel() {
  const cfg = useConfig().services;
  return (
    <div className="services-panel-grid">
      {cfg.items.map((s, i) => (
        <article key={s.n} className="service-card" data-cursor="hover">
          <div className="service-top">
            <span className="mono service-n">{`0${i + 1} / ${s.n}`}</span>
            <span className="mono service-tag">{s.tag}</span>
          </div>
          <h3 className="service-head display">{s.head}</h3>
          <p className="service-focus">{s.focus}</p>
          <ul className="service-outcomes">
            {s.outcomes.map((o) => (
              <li key={o}><span className="bullet">&#9679;</span>{o}</li>
            ))}
          </ul>
          <div className="service-foot">
            <a href={s.ctaHref} className={"pill-btn small" + (s.ctaStyle === "light" ? " is-light" : "")} data-cursor="hover">
              {s.ctaLabel} <span className="arrow">&rarr;</span>
            </a>
          </div>
        </article>
      ))}
    </div>
  );
}

window.AboutPanel    = AboutPanel;
window.WorkPanel     = WorkPanel;
window.JournalPanel  = JournalPanel;
window.SelectedWork  = SelectedWork;
window.Services      = Services;
window.ServicesPanel = ServicesPanel;
window.Testimonials  = Testimonials;
window.ContactBlock  = ContactBlock;
