// Into the Wild: home page (teaser for the next edition)

function HomeHero() {
  const x = NEXT_EDITION;
  return (
    <section className="hero" id="top">
      <div className="hero-bg" />
      <div className="hero-topo" />

      <h1 className="hero-headline">
        <span className="line">Back to</span>
        <span className="line outline">the forest.</span>
        <span className="line">This time,</span>
        <span className="line">
          <span className="marker"><span>survive it.</span></span>
        </span>
      </h1>

      <div className="hero-bottom">
        <div>
          <p className="hero-blurb">
            <em>Into the Wild</em> returns to Fragas do Eume Natural Park in
            June 2027 for its <em>fifth edition</em>: a survival challenge in one
            of the last Atlantic rainforests in Europe. Dates, details and how to
            apply are coming soon.
          </p>
          <a href="#notify" className="hero-cta">Tell me first <span aria-hidden="true">→</span></a>
        </div>
        <div className="hero-meta">
          <div className="meta-block">
            <span className="meta-label">Edition</span>
            <span className="meta-val">{x.roman}</span>
          </div>
          <div className="meta-block">
            <span className="meta-label">When</span>
            <span className="meta-val">{x.when}</span>
          </div>
          <div className="meta-block">
            <span className="meta-label">Where</span>
            <span className="meta-val">Fragas do Eume</span>
          </div>
        </div>
      </div>
    </section>);

}

function Teaser() {
  const known = [
  { k: "The place", v: "Fragas do Eume Natural Park, Galicia. The forest we explored in edition IV, now with fewer comforts." },
  { k: "The challenge", v: "Survival. Less gear, more forest, and a team you have not met yet." },
  { k: "The date", v: "June 2027. Exact dates will be announced soon." }];

  const soon = ["Exact dates", "Who can apply", "Partner countries", "How to apply"];

  return (
    <section className="section manifesto" id="next">
      <div className="wrap">
        <h2 className="section-title">
          Four editions <em>walked.</em>
          <br />The fifth one, <span className="outline">survived.</span>
        </h2>

        <div className="manifesto-grid">
          <p className="manifesto-lead">
            Three Caminos taught us to travel light. One forest taught us to
            <em> slow down.</em> In June 2027 we go back to Fragas do Eume to find
            out what we can do with even less.
          </p>
          <div>
            <dl className="known-list">
              {known.map((i) =>
              <div key={i.k} className="known-item">
                  <dt>{i.k}</dt>
                  <dd>{i.v}</dd>
                </div>
              )}
            </dl>
            <div className="soon">
              <span className="soon-label">Coming soon</span>
              <div className="edition-tags">
                {soon.map((s) => <span key={s} className="chip-dark">{s}</span>)}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

// EU member states: English name, ISO code and local names to search by.
const EU_COUNTRIES = [
{ name: "Austria", code: "AT", alt: ["Österreich"] },
{ name: "Belgium", code: "BE", alt: ["België", "Belgique", "Belgien"] },
{ name: "Bulgaria", code: "BG", alt: ["България", "Balgariya"] },
{ name: "Croatia", code: "HR", alt: ["Hrvatska"] },
{ name: "Cyprus", code: "CY", alt: ["Κύπρος", "Kypros", "Kıbrıs"] },
{ name: "Czechia", code: "CZ", alt: ["Česko", "Czech Republic"] },
{ name: "Denmark", code: "DK", alt: ["Danmark"] },
{ name: "Estonia", code: "EE", alt: ["Eesti"] },
{ name: "Finland", code: "FI", alt: ["Suomi"] },
{ name: "France", code: "FR", alt: [] },
{ name: "Germany", code: "DE", alt: ["Deutschland"] },
{ name: "Greece", code: "GR", alt: ["Ελλάδα", "Ellada", "Hellas"] },
{ name: "Hungary", code: "HU", alt: ["Magyarország"] },
{ name: "Ireland", code: "IE", alt: ["Éire"] },
{ name: "Italy", code: "IT", alt: ["Italia"] },
{ name: "Latvia", code: "LV", alt: ["Latvija"] },
{ name: "Lithuania", code: "LT", alt: ["Lietuva"] },
{ name: "Luxembourg", code: "LU", alt: ["Lëtzebuerg", "Luxemburg"] },
{ name: "Malta", code: "MT", alt: [] },
{ name: "Netherlands", code: "NL", alt: ["Nederland", "Holland"] },
{ name: "Poland", code: "PL", alt: ["Polska"] },
{ name: "Portugal", code: "PT", alt: [] },
{ name: "Romania", code: "RO", alt: ["România"] },
{ name: "Slovakia", code: "SK", alt: ["Slovensko"] },
{ name: "Slovenia", code: "SI", alt: ["Slovenija"] },
{ name: "Spain", code: "ES", alt: ["España", "Espanya", "Espainia"] },
{ name: "Sweden", code: "SE", alt: ["Sverige"] }];


const fold = (t) => t.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().trim();

function countryMatches(query) {
  const q = fold(query);
  if (!q) return EU_COUNTRIES;
  const score = (c) => {
    const names = [c.name, ...c.alt].map(fold);
    if (names.some((n) => n.startsWith(q)) || fold(c.code) === q) return 0;
    if (names.some((n) => n.split(/[\s-]/).some((w) => w.startsWith(q)))) return 1;
    if (names.some((n) => n.includes(q))) return 2;
    return -1;
  };
  return EU_COUNTRIES.
  map((c) => ({ c, s: score(c) })).
  filter((x) => x.s >= 0).
  sort((x, y) => x.s - y.s).
  map((x) => x.c);
}

function CountryCombobox({ id, name }) {
  const [query, setQuery] = React.useState('');
  const [value, setValue] = React.useState('');
  const [open, setOpen] = React.useState(false);
  const [active, setActive] = React.useState(0);
  const inputRef = React.useRef(null);
  const listRef = React.useRef(null);
  const options = countryMatches(query);
  const listId = `${id}-list`;

  // Only a country picked from the list is valid.
  React.useEffect(() => {
    const el = inputRef.current;
    if (!el) return;
    el.setCustomValidity(value ? '' : query ? 'Choose a country from the list.' : 'Select your country.');
  }, [value, query]);

  React.useEffect(() => {
    if (!open || !listRef.current) return;
    const item = listRef.current.children[active];
    if (item) item.scrollIntoView({ block: 'nearest' });
  }, [active, open]);

  const choose = (c) => {
    setValue(c.name);
    setQuery(c.name);
    setOpen(false);
  };

  const onChange = (e) => {
    const q = e.target.value;
    setQuery(q);
    setOpen(true);
    setActive(0);
    const exact = EU_COUNTRIES.find((c) => [c.name, ...c.alt].some((n) => fold(n) === fold(q)));
    setValue(exact ? exact.name : '');
  };

  const onKeyDown = (e) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      if (!open) {setOpen(true);return;}
      setActive((a) => Math.min(a + 1, options.length - 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setActive((a) => Math.max(a - 1, 0));
    } else if (e.key === 'Enter') {
      if (open && options[active]) {e.preventDefault();choose(options[active]);}
    } else if (e.key === 'Escape') {
      setOpen(false);
    } else if (e.key === 'Tab') {
      if (open && query && options.length === 1) choose(options[0]);
      setOpen(false);
    }
  };

  const onBlur = () => {
    setOpen(false);
    if (value) setQuery(value);
  };

  const selected = EU_COUNTRIES.find((c) => c.name === value);

  return (
    <div className={`combo ${open ? 'combo-open' : ''}`}>
      <div className="combo-field">
        {selected && <span className="combo-code" aria-hidden="true">{selected.code}</span>}
        <input
          ref={inputRef}
          id={id}
          type="text"
          role="combobox"
          aria-autocomplete="list"
          aria-expanded={open}
          aria-controls={listId}
          aria-activedescendant={open && options[active] ? `${id}-opt-${options[active].code}` : undefined}
          autoComplete="off"
          spellCheck={false}
          placeholder="Start typing your country"
          value={query}
          required
          onChange={onChange}
          onKeyDown={onKeyDown}
          onFocus={() => setOpen(true)}
          onClick={() => setOpen(true)}
          onBlur={onBlur} />
        <span className="combo-chev" aria-hidden="true">▾</span>
      </div>
      <input type="hidden" name={name} value={value} />
      {open &&
      <ul className="combo-list" role="listbox" id={listId} ref={listRef}>
          {options.length ?
        options.map((c, i) =>
        <li
          key={c.code}
          id={`${id}-opt-${c.code}`}
          role="option"
          aria-selected={i === active}
          className={`${i === active ? 'active' : ''} ${c.name === value ? 'chosen' : ''}`}
          onMouseDown={(e) => {e.preventDefault();choose(c);}}
          onMouseEnter={() => setActive(i)}>
                <span className="combo-code">{c.code}</span>
                <span className="combo-name">{c.name}</span>
                {c.alt[0] && fold(c.alt[0]) !== fold(c.name) && <span className="combo-alt">{c.alt[0]}</span>}
              </li>
        ) :
        <li className="combo-empty" role="option" aria-disabled="true" aria-selected="false">
              Only EU countries can join this edition.
            </li>
        }
        </ul>
      }
    </div>);

}

// Select-only dropdown with the same look and keyboard behaviour as the country picker.
function PickList({ id, name, options }) {
  const [value, setValue] = React.useState(options[0].value);
  const [open, setOpen] = React.useState(false);
  const [active, setActive] = React.useState(0);
  const listRef = React.useRef(null);
  const typed = React.useRef({ text: '', t: 0 });
  const listId = `${id}-list`;
  const current = options.find((o) => o.value === value);

  React.useEffect(() => {
    if (!open || !listRef.current) return;
    const item = listRef.current.children[active];
    if (item) item.scrollIntoView({ block: 'nearest' });
  }, [active, open]);

  const openList = () => {
    setActive(Math.max(0, options.findIndex((o) => o.value === value)));
    setOpen(true);
  };
  const choose = (o) => {setValue(o.value);setOpen(false);};

  const onKeyDown = (e) => {
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      e.preventDefault();
      if (!open) {openList();return;}
      setActive((a) => e.key === 'ArrowDown' ? Math.min(a + 1, options.length - 1) : Math.max(a - 1, 0));
    } else if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      if (open) choose(options[active]);else openList();
    } else if (e.key === 'Escape' || e.key === 'Tab') {
      setOpen(false);
    } else if (e.key.length === 1) {
      // Type the first letters or the edition number to jump to an option.
      const now = Date.now();
      typed.current = { text: (now - typed.current.t < 700 ? typed.current.text : '') + e.key.toLowerCase(), t: now };
      const i = options.findIndex((o) => [o.label, o.code, o.code.replace(/^0+/, ''), o.alt || ''].some((x) => fold(x).startsWith(typed.current.text)));
      if (i >= 0) {if (open) setActive(i);else setValue(options[i].value);}
    }
  };

  return (
    <div className={`combo ${open ? 'combo-open' : ''}`}>
      <div className="combo-field">
        <span className="combo-code" aria-hidden="true">{current.code}</span>
        <button
          type="button"
          id={id}
          className="combo-button"
          role="combobox"
          aria-haspopup="listbox"
          aria-expanded={open}
          aria-controls={listId}
          aria-activedescendant={open ? `${id}-opt-${active}` : undefined}
          onClick={() => open ? setOpen(false) : openList()}
          onKeyDown={onKeyDown}
          onBlur={() => setOpen(false)}>
          {current.label}{current.alt && <span className="combo-alt"> · {current.alt}</span>}
        </button>
        <span className="combo-chev" aria-hidden="true">▾</span>
      </div>
      <input type="hidden" name={name} value={value} />
      {open &&
      <ul className="combo-list" role="listbox" id={listId} ref={listRef} aria-labelledby={id}>
          {options.map((o, i) =>
        <li
          key={o.value}
          id={`${id}-opt-${i}`}
          role="option"
          aria-selected={o.value === value}
          className={`${i === active ? 'active' : ''} ${o.value === value ? 'chosen' : ''}`}
          onMouseDown={(e) => {e.preventDefault();choose(o);}}
          onMouseEnter={() => setActive(i)}>
              <span className="combo-code">{o.code}</span>
              <span className="combo-name">{o.label}</span>
              {o.alt && <span className="combo-alt">{o.alt}</span>}
            </li>
        )}
        </ul>
      }
    </div>);

}

function NotifyForm() {
  const [status, setStatus] = React.useState('idle'); // idle | sending | done | error
  const [error, setError] = React.useState('');

  const onSubmit = async (ev) => {
    ev.preventDefault();
    const form = ev.currentTarget;
    if (!form.reportValidity()) return;
    const data = new FormData(form);
    if (data.get('website')) {setStatus('done');return;} // honeypot
    data.append('page', window.location.pathname);
    data.append('edition', NEXT_EDITION.roman);
    setStatus('sending');
    setError('');
    try {
      // Apps Script web apps do not answer CORS preflights, so we send a
      // simple form-encoded POST and do not read the response.
      await fetch(NOTIFY_ENDPOINT, {
        method: 'POST',
        mode: 'no-cors',
        body: new URLSearchParams(data)
      });
      setStatus('done');
      form.reset();
    } catch (err) {
      setStatus('error');
      setError('We could not send the form. Check your connection and try again, or write to info@xeracion.org.');
    }
  };

  return (
    <section className="section notify" id="notify">
      <div className="notify-inner">
        <h2 className="big-title">
          Be the <em>first</em><br />to know.
        </h2>
        <p className="apply-sub">
          Leave your email and we will write to you when dates, details and
          applications for edition V are ready. No spam, just the forest.
        </p>

        {!NOTIFY_ENDPOINT ?
        <p className="notify-fallback">
            Write to <a href="mailto:info@xeracion.org?subject=Into%20the%20Wild%20V">info@xeracion.org</a> and
            we will add you to the list.
          </p> :
        status === 'done' ?
        <div className="notify-done" role="status">
            <strong>You're on the list.</strong>
            <span>We will write to you as soon as there is news about edition V.</span>
          </div> :

        <form className="notify-form" onSubmit={onSubmit} noValidate>
            <div className="field">
              <label htmlFor="nf-name">Name</label>
              <input id="nf-name" name="name" type="text" autoComplete="name" required maxLength={100} />
            </div>
            <div className="field">
              <label htmlFor="nf-email">Email</label>
              <input id="nf-email" name="email" type="email" autoComplete="email" required maxLength={150} />
            </div>
            <div className="field">
              <label htmlFor="nf-country">Country</label>
              <CountryCombobox id="nf-country" name="country" />
            </div>
            <div className="field">
              <label htmlFor="nf-past">Have you joined Into the Wild before?</label>
              <PickList
                id="nf-past"
                name="past"
                options={[
                { value: 'No', code: '✶', label: "No, it would be my first time" },
                ...EDITIONS.map((e) => ({ value: `Yes, ${e.name}`, code: e.roman, label: e.name, alt: e.year }))]} />
            </div>
            <div className="hp" aria-hidden="true">
              <label htmlFor="nf-website">Leave this empty</label>
              <input id="nf-website" name="website" type="text" tabIndex={-1} autoComplete="off" />
            </div>
            <label className="consent">
              <input type="checkbox" name="consent" value="yes" required />
              <span>
                I agree that Asociación Xeración stores these details to send me
                information about Into the Wild. I can ask to be removed at any
                time by writing to info@xeracion.org.
              </span>
            </label>
            <button type="submit" className="apply-btn" disabled={status === 'sending'}>
              {status === 'sending' ? 'Sending…' : 'Keep me posted'} <span className="arrow" aria-hidden="true">→</span>
            </button>
            {status === 'error' && <p className="notify-error" role="alert">{error}</p>}
          </form>
        }
      </div>
    </section>);

}

function PastEditions() {
  return (
    <section className="section editions" id="editions">
      <div className="wrap">
        <h2 className="section-title">
          Four <em>editions</em>
          <br />so <span className="outline">far.</span>
        </h2>
        <p className="section-intro">
          Editions I, II and III walked the yellow arrows to Santiago. Edition IV
          left the Camino for the forest. Each one has its own story.
        </p>

        <div className="editions-grid">
          {EDITIONS.map((e) =>
          <a key={e.n} href={editionUrl(e.n)} className="edition-card">
              <div className="edition-cover" style={{ backgroundImage: editionCover(e) }}>
                <span className="edition-num">{e.roman}</span>
                <span className="edition-year">{e.year}</span>
              </div>
              <div className="edition-body">
                <h3 className="edition-name">{e.name}</h3>
                <div className="edition-sub">{e.sub}</div>
                <div className="edition-meta">
                  {e.card.meta.map((m) => <span key={m}>{m}</span>)}
                </div>
                <p className="edition-text">{e.card.body}</p>
                <div className="edition-tags">
                  {e.card.tags.map((t) => <span key={t} className="chip-dark">{t}</span>)}
                </div>
                <span className="edition-more">Read the story →</span>
              </div>
            </a>
          )}
        </div>
      </div>
    </section>);

}

function HomePage() {
  return (
    <>
      <Nav />
      <main>
        <HomeHero />
        <Teaser />
        <NotifyForm />
        <PastEditions />
        <Testimonials
          id="voices"
          title={<>Don't take it <em>from us.</em></>}
          quotes={TESTIMONIALS} />
      </main>
      <Footer />
    </>);

}

Object.assign(window, { HomePage });
