/* global React, Nav, Footer, Tag, useApi, useTweaks, TweaksPanel, TweakSection, TweakSlider, TweakColor */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroTopPad": 64,
  "heroBottomPad": 88,
  "accent": "#5A54CF"
}/*EDITMODE-END*/;

const TC = {
  "Artificial Intelligence": "t-ai",
  "Implementation": "t-impl",
  "Research": "t-rsch",
  "Ethics": "t-eth",
  "Equity": "t-eq",
  "Education": "t-edu",
};
const TAG = {
  "Artificial Intelligence": "violet",
  "Implementation": "emerald",
  "Research": "blue",
  "Ethics": "amber",
  "Equity": "magenta",
  "Education": "ink",
};

/** Format an ISO YYYY-MM-DD into "Mon DD, YYYY". */
function formatDate(iso) {
  if (!iso) return "";
  const d = new Date(iso + "T12:00:00");
  if (isNaN(d.getTime())) return iso;
  return d.toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" });
}

/** Choose the most-relevant webinar for the home hero: upcoming if scheduled,
 *  otherwise the most recent archived one. */
function heroWebinar(blob) {
  if (!blob) return null;
  if (blob.upcoming) return { ...blob.upcoming, isUpcoming: true };
  if (blob.archive && blob.archive.length) return { ...blob.archive[0], isUpcoming: false };
  return null;
}

/** Pull the first listed speaker's name + affiliation. */
function speakerOf(w) {
  if (!w || !w.speakers || !w.speakers.length) return { name: "", aff: "" };
  const first = w.speakers.find(s => s.role === "speaker") || w.speakers[0];
  return {
    name: first.credentials ? `${first.name}, ${first.credentials}` : first.name,
    aff: first.affiliation || "",
  };
}

/** Extract an 11-char YouTube video ID from a URL, or null. */
function homeYoutubeId(url) {
  if (!url) return null;
  const m = url.match(/(?:youtu\.be\/|[?&]v=|youtube\.com\/embed\/|youtube\.com\/shorts\/)([A-Za-z0-9_-]{11})/);
  return m ? m[1] : null;
}

/** Mirror of thumbnailFor() from webinars.jsx for the home hero card.
 *  Speaker photo wins first — most engaging visual for a hero. */
function webinarThumb(w) {
  if (!w) return null;
  if (Array.isArray(w.speakers)) {
    const sp = w.speakers.find(s => s && s.photo && s.role !== "moderator")
            || w.speakers.find(s => s && s.photo);
    if (sp) return sp.photo;
  }
  if (w.thumbnail) return w.thumbnail;
  if (w.autoThumbnail !== false) {
    const id = homeYoutubeId(w.youtube);
    if (id) return `https://i.ytimg.com/vi/${id}/hqdefault.jpg`;
  }
  return null;
}

const PILLARS = [
  {
    id: "01",
    title: "Education",
    desc: "Increase clinical uptake and engagement with digital tools through a monthly webinar series, annual symposium, quarterly newsletter, and an updated open-access curriculum covering AI and the digital navigator role.",
    cta: "Monthly webinar series",
    to: "webinars.html",
    image: "images/education.png",
  },
  {
    id: "02",
    title: "AI Standards",
    desc: "Establish clear benchmarks for success and future innovation through initiatives like MindBench.ai, assessing reasoning, safety, and representativeness of AI tools across diverse populations.",
    cta: "Learn about AI standards",
    to: "ai-standards.html",
    image: "images/ai-standards.png",
  },
  {
    id: "03",
    title: "Digital Navigator Training",
    desc: "Provide training and support to facilitate broad implementation through structured, train-the-trainer programs that build digital literacy and workflow integration across diverse care settings, including low- and middle-income countries.",
    cta: "Navigator program",
    to: "digital-navigator-training.html",
    image: "images/digital-navigator-training.png",
  },
];

const BENEFITS = [
  "International networking",
  "Exclusive webinars",
  "Research collaboration",
  "Policy discussions",
  "Professional development",
];

const FEATURED_PAPER = {
  tag: "SODP · Featured",
  title: "Accelerating Digital Mental Health: The Society of Digital Psychiatry's Three-Pronged Road Map for Education, Digital Navigators, and AI",
  authors: "Torous J, Ledley KT, Gorban C, et al.",
  journal: "JMIR Mental Health",
  year: "2025",
  ref: "12:e84501",
  abstract: "Digital mental health tools such as apps, virtual reality, and artificial intelligence (AI) hold great promise but continue to face barriers to widespread clinical adoption. The Society of Digital Psychiatry, in partnership with JMIR Mental Health, presents a 3-pronged road map to accelerate their safe, effective, and equitable implementation. First, education: integrate digital psychiatry into core training and professional development…",
  href: "https://mental.jmir.org/2025/1/e84501",
};

const NEWS_TAG = {
  Announcement: "violet",
  Newsletter: "ink",
  Opportunity: "magenta",
  Publication: "blue",
  Press: "amber",
  Event: "emerald",
};

const { useState: _useState_home, useEffect: _useEffect_home } = React;

/** Rotating carousel of the news items marked `featured: true` in the admin.
 *  Auto-advances every 6s; pauses on hover. Renders nothing if there are
 *  zero featured items. */
function FeaturedNewsCarousel({ items, loading }) {
  const [idx, setIdx] = _useState_home(0);
  const [paused, setPaused] = _useState_home(false);

  _useEffect_home(() => {
    if (items.length <= 1 || paused) return;
    const id = setInterval(() => setIdx(i => (i + 1) % items.length), 9000);
    return () => clearInterval(id);
  }, [items.length, paused]);

  // Keep idx in range when the list shrinks (e.g. admin unfeatures an item).
  _useEffect_home(() => {
    if (idx >= items.length && items.length > 0) setIdx(0);
  }, [items.length, idx]);

  if (loading && items.length === 0) {
    return (
      <article className="hero-poster hero-poster-news hero-poster-loading" aria-hidden="true">
        <div className="hero-poster-link">
          <div className="hero-poster-text">
            <div className="hero-poster-eyebrow-row"><span className="eyebrow">Loading…</span></div>
          </div>
          <div className="hero-poster-cat-panel cat-ink" />
        </div>
      </article>
    );
  }
  if (items.length === 0) {
    return (
      <article className="hero-poster hero-poster-news">
        <a href="news.html" className="hero-poster-link">
          <div className="hero-poster-text">
            <div className="hero-poster-eyebrow-row"><span className="eyebrow">News</span></div>
            <h3 className="hero-poster-title">Latest updates from the Society</h3>
          </div>
          <div className="hero-poster-cat-panel cat-violet">
            <div className="hero-poster-cat-name">News</div>
          </div>
        </a>
      </article>
    );
  }

  const n = items[idx % items.length];
  const href = n.link || "news.html";
  const isExternal = !!n.link;
  const catColor = NEWS_TAG[n.cat] || "violet";

  // Overlay control strip: dots (only if multiple items) + permanent "All news →"
  // affordance so users can always escape to the index, even with a single feature.
  const controls = (
    <div className="hero-poster-controls">
      {items.length > 1 && (
        <div className="hero-poster-dots" role="tablist" aria-label="Featured news pagination">
          {items.map((_, i) => (
            <button
              key={i}
              role="tab"
              aria-selected={i === idx}
              className={i === idx ? "is-active" : ""}
              onClick={(e) => { e.stopPropagation(); setIdx(i); }}
              aria-label={`Show item ${i + 1}`}
            />
          ))}
        </div>
      )}
      <a href="news.html" className="hero-poster-all-link" onClick={e => e.stopPropagation()}>All news →</a>
    </div>
  );

  // Newsletter cards are special: the title (issue name) goes in a header
  // strip at the top, with the newsletter cover image filling the area below.
  if (n.cat === "Newsletter") {
    return (
      <article
        key={`nl-${idx}`}
        className="hero-poster hero-poster-newsletter hero-poster-anim"
        onMouseEnter={() => setPaused(true)}
        onMouseLeave={() => setPaused(false)}
      >
        <a
          href={href}
          target={isExternal ? "_blank" : undefined}
          rel={isExternal ? "noreferrer" : undefined}
          className="hero-poster-newsletter-link"
          aria-label={n.title}
        >
          <div className="hero-poster-newsletter-head">
            <div className="hero-poster-newsletter-eyebrow">
              <span className="eyebrow">Newsletter</span>
              <span className="hero-poster-date">{formatDate(n.date)}</span>
            </div>
            <div className="hero-poster-newsletter-name">{n.title}</div>
          </div>
          {n.image ? (
            <img src={n.image} alt={n.title || "Newsletter"} className="hero-poster-newsletter-img" />
          ) : (
            <div className="hero-poster-cat-panel cat-ink" aria-hidden="true">
              <div className="hero-poster-cat-name">Newsletter</div>
            </div>
          )}
        </a>
        {controls}
      </article>
    );
  }

  // When admin uploaded a complete social card image, let it BE the card.
  // The image already carries the title, author, and branding — adding another
  // title beside it is the very clash we keep running into.
  if (n.image) {
    return (
      <article
        key={`nf-${idx}`}
        className="hero-poster hero-poster-news-full hero-poster-anim"
        onMouseEnter={() => setPaused(true)}
        onMouseLeave={() => setPaused(false)}
      >
        <a
          href={href}
          target={isExternal ? "_blank" : undefined}
          rel={isExternal ? "noreferrer" : undefined}
          className="hero-poster-news-full-link"
          aria-label={n.title}
        >
          <img src={n.image} alt={n.title || "Featured news"} className="hero-poster-news-full-img" />
        </a>
        {controls}
      </article>
    );
  }

  // No image: fall back to the category-colored typographic panel layout.
  return (
    <article
      key={`np-${idx}`}
      className="hero-poster hero-poster-news hero-poster-anim"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      <a href={href} target={isExternal ? "_blank" : undefined} rel={isExternal ? "noreferrer" : undefined} className="hero-poster-link">
        <div className="hero-poster-text">
          <div className="hero-poster-eyebrow-row">
            <span className="eyebrow">Featured · News</span>
            <span className="hero-poster-date">{formatDate(n.date)}</span>
          </div>
          <h3 className="hero-poster-title">{n.title}</h3>
          {n.body && <div className="hero-poster-body">{n.body.split(/\n+/)[0]}</div>}
        </div>
        <div className={`hero-poster-cat-panel cat-${catColor}`} aria-hidden="true">
          <div className="hero-poster-cat-label">Featured</div>
          <div className="hero-poster-cat-name">{n.cat}</div>
        </div>
      </a>
      {controls}
    </article>
  );
}

/* ────────────────────────────────────────────────────────── */

/** Poster-style webinar card: large image up top, text below.
 *  Tag overlays the image. For upcoming sessions the text area is dark indigo. */
function HeroWebinarCard({ w, loading }) {
  if (loading && !w) {
    return (
      <article className="hero-poster hero-poster-loading" aria-hidden="true">
        <div className="hero-poster-link">
          <div className="hero-poster-text">
            <div className="hero-poster-eyebrow-row"><span className="eyebrow">Loading…</span></div>
            <div className="hero-poster-title" style={{ background: "var(--rule)", color: "transparent", borderRadius: 3, minHeight: 22 }}>Loading…</div>
          </div>
          <div className="hero-poster-image hero-poster-image-empty" />
        </div>
      </article>
    );
  }
  if (!w) {
    return (
      <article className="hero-poster">
        <a href="webinars.html" className="hero-poster-link">
          <div className="hero-poster-text">
            <div className="hero-poster-eyebrow-row"><span className="eyebrow">Webinars</span></div>
            <div className="hero-poster-title">Monthly sessions on digital psychiatry</div>
          </div>
          <div className="hero-poster-image hero-poster-image-empty">
            <div className="hero-poster-fill">WEB</div>
          </div>
        </a>
      </article>
    );
  }

  const sp = speakerOf(w);
  const dateLabel = w.isUpcoming ? "Upcoming · " + formatDate(w.date) : formatDate(w.date);
  const href = w.slug ? `/webinar-detail?id=${encodeURIComponent(w.slug)}` : "webinars.html";
  const eyebrow = w.isUpcoming ? "Next session" : "Latest session";
  const thumb = webinarThumb(w);
  const topicClass = TC[w.topic] || "";

  return (
    <article className={`hero-poster hero-poster-webinar ${w.isUpcoming ? "is-upcoming" : ""}`}>
      <a href={href} className="hero-poster-link">
        <div className="hero-poster-text">
          <div className="hero-poster-eyebrow-row">
            <span className="eyebrow">{eyebrow}</span>
            <span className="hero-poster-date">{dateLabel}</span>
          </div>
          <div className="hero-poster-tag-row">
            <Tag kind={TAG[w.topic] || "violet"}>{w.topic}</Tag>
          </div>
          <h3 className="hero-poster-title">{w.title}</h3>
          {sp.name && <div className="hero-poster-body">{sp.name}{sp.aff && ` · ${sp.aff.split(";")[0]}`}</div>}
        </div>
        <div
          className={`hero-poster-image ${thumb ? "" : "hero-poster-image-empty"}`}
          data-topic={topicClass}
          style={thumb ? { backgroundImage: `url(${thumb})` } : undefined}
          aria-hidden="true"
        >
          {!thumb && <div className="hero-poster-fill">{w.topic.slice(0, 3).toUpperCase()}</div>}
        </div>
      </a>
    </article>
  );
}

/* ────────────────────────────────────────────────────────── */

function Hero({ t, featured, webinarsLoading, featuredNews, newsLoading }) {
  return (
    <section style={{ padding: `${t.heroTopPad}px 0 ${t.heroBottomPad}px`, borderBottom: "1px solid var(--rule)" }}>
      <div className="wrap">
        <div className="grid-hero">
          {/* LEFT brand pitch */}
          <div style={{ display: "flex", flexDirection: "column" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 24 }}>
              <span className="rule-thick" style={{ background: t.accent }} />
              <span className="eyebrow">Connecting people</span>
            </div>
            <h1 className="t-display">
              An international hub for digital psychiatry professionals.
            </h1>
            <p className="lede" style={{ marginTop: 20, maxWidth: 540 }}>
              In partnership with <em>JMIR Mental Health</em>, linking clinicians, researchers, and technologists across 50+ countries to share knowledge, advance evidence, and set standards for AI and digital tools in mental health.
            </p>
            <div style={{ flex: 1, minHeight: 24 }} />
            <div style={{ display: "flex", gap: 12, alignItems: "center", marginTop: 28, flexWrap: "wrap" }}>
              <a href="https://share.hsforms.com/10PV_ENANSJqqA-pAWE3hfgbpk19" target="_blank" rel="noreferrer" className="btn btn-primary" style={{ background: t.accent }}>Apply to Join</a>
              <a href="members.html" className="link" style={{ color: t.accent }}>Meet the leadership board →</a>
            </div>
          </div>

          {/* RIGHT — two stacked cards: webinar + featured news carousel */}
          <div className="hero-stack">
            <HeroWebinarCard w={featured} loading={webinarsLoading} />
            <FeaturedNewsCarousel items={featuredNews} loading={newsLoading} />
          </div>
        </div>
      </div>
    </section>
  );
}

/* ────────────────────────────────────────────────────────── */

function StatStrip() {
  return (
    <section style={{ padding: "72px 0", borderBottom: "1px solid var(--rule)" }}>
      <div className="wrap">
        <div className="section-head">
          <div className="head-l">
            <span className="num">/ 02</span>
            <span className="eyebrow">By the numbers</span>
          </div>
          <span className="caption mono" style={{ color: "var(--ink-4)", fontSize: 11, letterSpacing: "0.06em" }}>
            Updated May 1, 2026
          </span>
        </div>
        <div className="stat-row stat-row-5">
          <div className="stat-cell">
            <div className="num">550+</div>
            <div className="label">Members</div>
            <div className="delta">▲ growing</div>
          </div>
          <div className="stat-cell">
            <div className="num">50+</div>
            <div className="label">Countries</div>
          </div>
          <div className="stat-cell">
            <div className="num">11</div>
            <div className="label">Co-leaders</div>
          </div>
          <div className="stat-cell">
            <div className="num">7</div>
            <div className="label">Partner sites</div>
          </div>
          <div className="stat-cell">
            <div className="num">24</div>
            <div className="label">Webinars hosted</div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ────────────────────────────────────────────────────────── */

function RoadMap() {
  return (
    <section style={{ padding: "96px 0", background: "var(--bg-soft)", borderBottom: "1px solid var(--rule)" }}>
      <div className="wrap">
        <div className="section-head">
          <div className="head-l">
            <span className="num">/ 03</span>
            <span className="eyebrow">The Three-Pronged Road Map</span>
          </div>
        </div>

        <div className="grid-intro" style={{ marginBottom: 36 }}>
          <h2 className="t-h1" style={{ fontFamily: "var(--type-serif)", fontWeight: 500 }}>
            A tripartite model for digital mental health.
          </h2>
          <p className="body" style={{ color: "var(--ink-3)" }}>
            SODP and <em>JMIR Mental Health</em> have outlined three pillars to move digital mental health from research into routine care: <strong>education</strong>, <strong>AI standards</strong>, and <strong>digital navigator training</strong>. Together they bridge the gap between evidence and implementation.
          </p>
        </div>

        <div className="pillar-grid">
          {PILLARS.map(p => (
            <div key={p.id} className="pillar-card">
              <div className="pillar-image">
                <img src={p.image} alt="" loading="lazy" />
              </div>
              <div className="pillar-head">
                <span className="pillar-num">/ {p.id}</span>
              </div>
              <h3 className="pillar-title">{p.title}</h3>
              <p className="pillar-desc">{p.desc}</p>
              <a
                href={p.to}
                className="link pillar-cta"
                {...(p.external ? { target: "_blank", rel: "noreferrer" } : {})}
              >
                {p.cta} →
              </a>
            </div>
          ))}
        </div>

        <p className="citation">
          Adapted from: Torous J, et al. Accelerating Digital Mental Health: The Society of Digital Psychiatry's Three-Pronged Road Map for Education, Digital Navigators, and AI. <em>JMIR Ment Health</em> 2025;12:e84501.
        </p>
      </div>
    </section>
  );
}

/* ────────────────────────────────────────────────────────── */

function GlobalNetwork() {
  return (
    <section style={{ padding: "96px 0", borderBottom: "1px solid var(--rule)" }}>
      <div className="wrap">
        <div className="section-head">
          <div className="head-l">
            <span className="num">/ 04</span>
            <span className="eyebrow">Global Network</span>
          </div>
          <span className="caption mono" style={{ color: "var(--ink-4)", fontSize: 11, letterSpacing: "0.06em" }}>
            550+ members · 50+ countries
          </span>
        </div>

        <div className="grid-network">
          <div style={{ display: "flex", flexDirection: "column" }}>
            <h2 className="t-h2" style={{ fontFamily: "var(--type-serif)", fontWeight: 500 }}>
              Connecting experts and practitioners worldwide.
            </h2>
            <p className="body" style={{ color: "var(--ink-3)", marginTop: 18 }}>
              An interprofessional community of clinicians, researchers, and trainees from more than fifty countries, sharing knowledge and best practices in digital mental health.
            </p>
            <ul className="benefits-list">
              {BENEFITS.map(b => <li key={b}>{b}</li>)}
            </ul>
            <div style={{ marginTop: 28 }}>
              <a href="https://share.hsforms.com/10PV_ENANSJqqA-pAWE3hfgbpk19" target="_blank" rel="noreferrer" className="link">Become a member →</a>
            </div>
          </div>

          <figure className="map-frame">
            <img
              src="images/World Map.png"
              alt="World map highlighting countries with SODP members across six continents."
            />
            <figcaption>Member distribution across 50+ countries.</figcaption>
          </figure>
        </div>
      </div>
    </section>
  );
}

/* ────────────────────────────────────────────────────────── */

function Publications() {
  const p = FEATURED_PAPER;
  return (
    <section style={{ padding: "96px 0", borderBottom: "1px solid var(--rule)" }}>
      <div className="wrap">
        <div className="section-head">
          <div className="head-l">
            <span className="num">/ 05</span>
            <span className="eyebrow">SODP Publications</span>
          </div>
        </div>

        <a href={p.href} target="_blank" rel="noreferrer" className="pub-card">
          <span className="pub-tag">{p.tag}</span>
          <h3 className="pub-title">{p.title}</h3>
          <div className="pub-meta">
            <span>{p.authors}</span>
            <span className="pub-meta-sep">·</span>
            <span><em>{p.journal}</em> · {p.year} · <span className="mono">{p.ref}</span></span>
          </div>
          <p className="pub-abstract">{p.abstract}</p>
          <span className="pub-link">Read on JMIR →</span>
        </a>
      </div>
    </section>
  );
}

/* ────────────────────────────────────────────────────────── */

function NewsStrip() {
  const { data, loading } = useApi("news", []);
  const items = Array.isArray(data) ? data.slice(0, 3) : [];

  // Hide the section entirely if there's no news to show yet.
  if (!loading && items.length === 0) return null;

  return (
    <section style={{ padding: "96px 0", borderBottom: "1px solid var(--rule)" }}>
      <div className="wrap">
        <div className="section-head">
          <div className="head-l">
            <span className="num">/ 06</span>
            <span className="eyebrow">Recent updates</span>
          </div>
          <a href="news.html" className="link">All news →</a>
        </div>

        <div className="table-scroll">
          <table className="data-table">
            <thead>
              <tr>
                <th style={{ width: 130 }}>Date</th>
                <th style={{ width: 130 }}>Category</th>
                <th>Headline</th>
                <th style={{ width: 56 }}></th>
              </tr>
            </thead>
            <tbody>
              {items.map(n => (
                <tr
                  key={n.id || n.slug}
                  onClick={() => {
                    window.location.href = n.slug
                      ? `/news-detail?id=${encodeURIComponent(n.slug)}`
                      : (n.link || "news.html");
                  }}
                  style={{ cursor: "pointer" }}
                >
                  <td className="col-mono">{formatDate(n.date)}</td>
                  <td><Tag kind={NEWS_TAG[n.cat] || "violet"}>{n.cat}</Tag></td>
                  <td><strong style={{ fontSize: 15, color: "var(--ink)" }}>{n.title}</strong></td>
                  <td style={{ textAlign: "right", color: "var(--indigo-500)" }}>→</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </section>
  );
}

/* ────────────────────────────────────────────────────────── */

function HomePage() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const { data: webinars, loading: webinarsLoading } = useApi("webinars", { upcoming: null, archive: [] });
  const { data: newsData, loading: newsLoading } = useApi("news", []);
  const featured = heroWebinar(webinars);
  const featuredNews = Array.isArray(newsData) ? newsData.filter(n => n && n.featured) : [];
  return (
    <>
      <Nav active="home" />
      <Hero
        t={t}
        featured={featured}
        webinarsLoading={webinarsLoading}
        featuredNews={featuredNews}
        newsLoading={newsLoading}
      />
      <StatStrip />
      <RoadMap />
      <GlobalNetwork />
      <Publications />
      <NewsStrip />
      <Footer />
      <TweaksPanel>
        <TweakSection label="Hero" />
        <TweakSlider label="Top padding" value={t.heroTopPad} min={16} max={160} unit="px"
                     onChange={v => setTweak('heroTopPad', v)} />
        <TweakSlider label="Bottom padding" value={t.heroBottomPad} min={16} max={160} unit="px"
                     onChange={v => setTweak('heroBottomPad', v)} />
        <TweakSection label="Brand" />
        <TweakColor label="Accent" value={t.accent}
                    onChange={v => setTweak('accent', v)} />
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<HomePage />);
