/* Saints Calendar — Search results, Browse views (Patronage, Orders, Timeline, Map), About */

const SearchView = ({ query, setQuery, onOpenSaint, onSearch }) => {
  const [filters, setFilters] = React.useState({ era: null, region: null, classification: null, order: null });

  const matches = React.useMemo(() => {
    const q = (query || "").toLowerCase().trim();
    return window.SAINTS.filter(s => {
      if (filters.era && !s.centuries.includes(filters.era)) return false;
      if (filters.region && s.region !== filters.region) return false;
      if (filters.classification && s.classification !== filters.classification) return false;
      if (filters.order && (!s.order || !s.order.toLowerCase().includes(filters.order.toLowerCase()))) return false;
      if (!q) return true;
      const hay = [
        s.name, s.honorific, s.epithet, s.summary, s.region, s.order || "",
        ...(s.titles || []), ...(s.patronage || []), ...(s.attributes || []),
        ...(s.tradition || []), s.classification,
        s.bio.earlyLife, s.bio.ministry, s.bio.legacy
      ].join(" ").toLowerCase();
      // Century like "13th century" → 13
      const centMatch = q.match(/(\d+)(st|nd|rd|th)\s*c/);
      if (centMatch && s.centuries.includes(parseInt(centMatch[1]))) return true;
      return hay.includes(q);
    });
  }, [query, filters]);

  const allRegions = [...new Set(window.SAINTS.map(s => s.region))];
  const allClassifications = [...new Set(window.SAINTS.map(s => s.classification))];
  const allOrders = [...new Set(window.SAINTS.map(s => s.order).filter(Boolean))];

  const setF = (key, val) => setFilters(f => ({ ...f, [key]: f[key] === val ? null : val }));

  return (
    <div className="view-enter">
      <section style={{ padding: "48px 0 24px" }}>
        <div className="container">
          <div className="t-rubric mb-2">Search the Corpus</div>
          <form onSubmit={(e) => { e.preventDefault(); onSearch(query); }} style={{ marginBottom: 24 }}>
            <div className="search-shell">
              <IconSearch size={18} />
              <input
                type="text"
                placeholder="Search saints, patronages, places, eras…"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                style={{ marginLeft: 14 }}
                autoFocus
              />
              <span className="t-meta">{matches.length} {matches.length === 1 ? "result" : "results"}</span>
            </div>
          </form>
        </div>
      </section>

      <section>
        <div className="container" style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 56, alignItems: "start" }}>
          {/* Filters */}
          <aside style={{ position: "sticky", top: 88 }}>
            <div className="t-rubric mb-3">Filters</div>
            <FilterGroup title="Classification">
              {allClassifications.map(c => (
                <FilterChip key={c} active={filters.classification === c} onClick={() => setF("classification", c)}>
                  {c.charAt(0).toUpperCase() + c.slice(1)}
                </FilterChip>
              ))}
            </FilterGroup>
            <FilterGroup title="Region">
              {allRegions.map(r => (
                <FilterChip key={r} active={filters.region === r} onClick={() => setF("region", r)}>{r}</FilterChip>
              ))}
            </FilterGroup>
            <FilterGroup title="Century">
              {[1, 4, 5, 11, 12, 13, 15, 16, 19].map(c => (
                <FilterChip key={c} active={filters.era === c} onClick={() => setF("era", c)}>{c}{c===1?"st":c===2?"nd":c===3?"rd":"th"} c.</FilterChip>
              ))}
            </FilterGroup>
            <FilterGroup title="Order">
              {allOrders.map(o => (
                <FilterChip key={o} active={filters.order === o} onClick={() => setF("order", o)}>{o.split(" ")[0]}</FilterChip>
              ))}
            </FilterGroup>
            {(filters.era || filters.region || filters.classification || filters.order) && (
              <button className="btn btn-ghost btn-sm mt-3" onClick={() => setFilters({})}>Clear filters</button>
            )}
          </aside>

          {/* Results */}
          <div>
            {matches.length === 0 ? (
              <div className="text-center" style={{ padding: "80px 0", color: "var(--ink-mute)" }}>
                <Fleuron />
                <p style={{ fontFamily: "var(--font-display)", fontSize: 22, fontStyle: "italic", marginTop: 16 }}>
                  No saint of that name in our corpus.
                </p>
              </div>
            ) : (
              matches.map(s => <SaintListItem key={s.id} saint={s} onOpen={onOpenSaint} />)
            )}
          </div>
        </div>
      </section>
    </div>
  );
};

const FilterGroup = ({ title, children }) => (
  <div style={{ marginBottom: 20 }}>
    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.16em", textTransform: "uppercase", color: "var(--ink-mute)", marginBottom: 8 }}>{title}</div>
    <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>{children}</div>
  </div>
);
const FilterChip = ({ active, onClick, children }) => (
  <button className={`chip ${active ? "active" : ""}`} onClick={onClick}>{children}</button>
);

// ---- Patronage browser ----
const PatronageView = ({ onOpenSaint }) => {
  const map = {};
  window.SAINTS.forEach(s => s.patronage.forEach(p => {
    if (!map[p]) map[p] = [];
    map[p].push(s);
  }));
  const sorted = Object.entries(map).sort((a, b) => a[0].localeCompare(b[0]));

  const groups = {
    "Vocations & Work": ["Theologians", "Workers", "Soldiers", "Educators", "Students", "Booksellers", "Printers", "Brewers", "Florists", "Merchants", "Engineers", "Pharmacists", "Lacemakers", "Embroiderers", "Goldsmiths", "Mothers", "Wives", "Fathers", "Midwives", "Travellers", "Aviators", "Radio operators", "Pastry chefs", "Hatters", "Spiritual writers", "Chimney sweeps", "Laundry workers", "Dairymaids", "Universities", "Catholic schools", "Spiritual exercises", "Mystics", "Contemplatives", "Spanish poets", "Hermits", "Healings"],
    "Places & Peoples": ["Italy", "Ireland", "France", "Spain", "Poland", "Lebanon", "Belgium", "Canada", "Mexico", "Russia", "Cyprus", "Uruguay", "Nigeria", "Austria", "The Basque Country", "City of Hippo", "Kraków", "Universal Church", "Coptic Christians", "Order of the White Eagle"],
    "Causes & Conditions": ["Sore eyes", "Eye disease", "Headache sufferers", "Cattle", "Newborns", "Television", "Lost things", "The poor", "Captives", "Martyrs", "Abuse victims", "Rape victims", "Mental illness", "Difficult marriages", "Disappointing children", "Pregnant women", "Animals", "Ecology", "Stowaways", "AIDS sufferers", "Missions", "Speleologists", "Against poisoning", "Against snakes", "A happy death", "Poets"],
  };

  return (
    <div className="view-enter">
      <section style={{ padding: "48px 0 32px" }}>
        <div className="container">
          <div className="t-rubric mb-2">Browse</div>
          <h1 className="t-display" style={{ fontSize: 56, marginBottom: 12 }}>Patronage</h1>
          <p style={{ fontSize: 18, color: "var(--ink-soft)", maxWidth: 640 }}>
            The saints have, by long Christian custom, been associated with vocations, places, illnesses, and causes —
            invoked by farmers and aviators, the dying and the gravely ill.
          </p>
        </div>
      </section>

      {Object.entries(groups).map(([groupName, items]) => {
        const present = items.filter(i => map[i]);
        if (!present.length) return null;
        return (
          <section key={groupName} style={{ padding: "32px 0", borderTop: "1px solid var(--hairline-soft)" }}>
            <div className="container">
              <div className="t-rubric mb-3" style={{ color: "var(--gilt-deep)" }}>{groupName}</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 20 }}>
                {present.map(p => (
                  <div key={p}>
                    <div style={{ fontFamily: "var(--font-display)", fontSize: 19, marginBottom: 4, fontStyle: "italic" }}>{p}</div>
                    <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
                      {map[p].map(s => (
                        <button key={s.id} onClick={() => onOpenSaint(s.id)}
                          style={{ textAlign: "left", color: "var(--ink-soft)", fontSize: 15, padding: "2px 0" }}
                          onMouseEnter={(e) => e.currentTarget.style.color = "var(--gilt-deep)"}
                          onMouseLeave={(e) => e.currentTarget.style.color = "var(--ink-soft)"}
                        >
                          {s.honorific} {s.name}
                        </button>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </section>
        );
      })}
    </div>
  );
};

// ---- Orders browser ----
const OrdersView = ({ onOpenSaint }) => {
  const map = {};
  window.SAINTS.forEach(s => {
    const o = s.order || "Diocesan / Lay / No order";
    if (!map[o]) map[o] = [];
    map[o].push(s);
  });
  const orderDescriptions = {
    "Franciscan (O.F.M.)": "Founded 1209 by Francis of Assisi. The Friars Minor live a life of poverty and itinerant preaching.",
    "Dominicans (O.P.)": "Founded 1216 by Dominic Guzmán. The Order of Preachers, devoted to study and the salvation of souls.",
    "Benedictines (O.S.B.)": "Founded c. 530 by Benedict of Nursia. The first stable rule of Western monasticism — ora et labora.",
    "Discalced Carmelites (O.C.D.)": "Reformed branch of the Carmelite order, established by Teresa of Ávila and John of the Cross in 1568.",
    "Society of Jesus (S.J.)": "Founded 1540 by Ignatius of Loyola. Soldiers of Christ, devoted to mission, education, and obedience to the pope.",
    "Poor Clares (O.S.C.)": "Founded 1212 by Clare of Assisi. The female Franciscan order, fully enclosed and contemplative.",
    "Lebanese Maronite Order (O.L.M.)": "Founded 1695 in Lebanon. The principal Maronite religious order, contemplative and active.",
  };

  return (
    <div className="view-enter">
      <section style={{ padding: "48px 0 32px" }}>
        <div className="container">
          <div className="t-rubric mb-2">Browse</div>
          <h1 className="t-display" style={{ fontSize: 56, marginBottom: 12 }}>Religious Orders</h1>
          <p style={{ fontSize: 18, color: "var(--ink-soft)", maxWidth: 640 }}>
            From the cenobites of the Egyptian desert to the friar preachers of medieval Europe, religious orders
            shaped both holiness and history.
          </p>
        </div>
      </section>

      <div className="container">
        {Object.entries(map).map(([order, saints]) => (
          <div key={order} style={{ padding: "40px 0", borderTop: "1px solid var(--hairline-soft)" }}>
            <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 56, alignItems: "start" }}>
              <div>
                <div className="t-rubric mb-2" style={{ color: "var(--gilt-deep)" }}>{saints.length} {saints.length === 1 ? "Saint" : "Saints"}</div>
                <h2 className="t-display" style={{ fontSize: 32, marginBottom: 12 }}>{order}</h2>
                {orderDescriptions[order] && (
                  <p style={{ fontSize: 15, color: "var(--ink-soft)", lineHeight: 1.6, fontStyle: "italic" }}>
                    {orderDescriptions[order]}
                  </p>
                )}
              </div>
              <div>
                {saints.map(s => <SaintListItem key={s.id} saint={s} onOpen={onOpenSaint} />)}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ---- Timeline view ----
const TimelineView = ({ onOpenSaint }) => {
  const minCent = -1, maxCent = 21;
  const sorted = [...window.SAINTS].sort((a, b) => a.dates.born - b.dates.born);
  // Group by century
  const byCent = {};
  sorted.forEach(s => {
    const c = Math.ceil(s.dates.born / 100) || 1;
    const cKey = s.dates.born < 0 ? 0 : c;
    if (!byCent[cKey]) byCent[cKey] = [];
    byCent[cKey].push(s);
  });

  const centuries = Object.keys(byCent).map(Number).sort((a,b) => a-b);

  return (
    <div className="view-enter">
      <section style={{ padding: "48px 0 32px" }}>
        <div className="container">
          <div className="t-rubric mb-2">Browse</div>
          <h1 className="t-display" style={{ fontSize: 56, marginBottom: 12 }}>Timeline</h1>
          <p style={{ fontSize: 18, color: "var(--ink-soft)", maxWidth: 640 }}>
            From the apostolic age to the twentieth century.
          </p>
        </div>
      </section>

      <div className="container" style={{ paddingBottom: 60 }}>
        {centuries.map(c => (
          <div key={c} style={{ display: "grid", gridTemplateColumns: "180px 1fr", gap: 40, padding: "32px 0", borderTop: "1px solid var(--hairline-soft)" }}>
            <div style={{ position: "sticky", top: 88, alignSelf: "start" }}>
              <div style={{ fontFamily: "var(--font-display)", fontSize: 56, color: "var(--gilt-deep)", lineHeight: 1 }}>
                {c === 0 ? "I" : c}<sup style={{ fontSize: 20 }}>{c===1?"st":c===2?"nd":c===3?"rd":c===0?"st":"th"}</sup>
              </div>
              <div className="t-meta">{c === 0 ? "1st c." : `${c}${c===1?"st":c===2?"nd":c===3?"rd":"th"} century`}</div>
              <div className="t-meta mt-1">{byCent[c].length} saint{byCent[c].length>1?"s":""}</div>
            </div>
            <div>
              {byCent[c].map(s => (
                <button key={s.id} onClick={() => onOpenSaint(s.id)} style={{
                  display: "block", width: "100%", textAlign: "left",
                  padding: "16px 0", borderBottom: "1px solid var(--hairline-soft)",
                }}>
                  <div className="flex items-baseline gap-3">
                    <span className="t-meta" style={{ width: 100, flexShrink: 0 }}>{yearLabel(s.dates.born)}–{yearLabel(s.dates.died)}</span>
                    <span style={{ fontFamily: "var(--font-display)", fontSize: 22 }}>{s.honorific} {s.name}</span>
                    <span style={{ color: "var(--ink-mute)", fontStyle: "italic", fontSize: 14, marginLeft: "auto" }}>{s.epithet}</span>
                  </div>
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ---- Map view (placeholder with regional list) ----
const MapView = ({ onOpenSaint }) => {
  const byRegion = {};
  window.SAINTS.forEach(s => {
    if (!byRegion[s.region]) byRegion[s.region] = [];
    byRegion[s.region].push(s);
  });

  return (
    <div className="view-enter">
      <section style={{ padding: "48px 0 32px" }}>
        <div className="container">
          <div className="t-rubric mb-2">Browse</div>
          <h1 className="t-display" style={{ fontSize: 56, marginBottom: 12 }}>Map of Holiness</h1>
          <p style={{ fontSize: 18, color: "var(--ink-soft)", maxWidth: 640 }}>
            Birthplaces, episcopal sees, monastic foundations, and shrines that hold the relics of the saints.
          </p>
        </div>
      </section>

      <div className="container">
        <div className="placeholder-art" style={{ aspectRatio: "16/7", marginBottom: 40 }}>
          <span>Interactive Map · Drop in a stylised antique map<br/>with pins for birthplaces, sees, and shrines</span>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 28 }}>
          {Object.entries(byRegion).map(([region, saints]) => (
            <div key={region} className="card">
              <div className="t-rubric mb-2" style={{ color: "var(--gilt-deep)" }}>{region}</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                {saints.map(s => (
                  <button key={s.id} onClick={() => onOpenSaint(s.id)}
                    style={{ textAlign: "left", fontFamily: "var(--font-display)", fontSize: 17 }}
                    onMouseEnter={(e) => e.currentTarget.style.color = "var(--gilt-deep)"}
                    onMouseLeave={(e) => e.currentTarget.style.color = "var(--ink)"}
                  >
                    {s.honorific} {s.name}
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ---- About ----
const AboutView = () => (
  <div className="view-enter">
    <section style={{ padding: "72px 0" }}>
      <div className="container-narrow">
        <div className="t-rubric text-center mb-3">Colophon</div>
        <h1 className="t-display text-center" style={{ fontSize: 64, marginBottom: 8 }}>About this Calendar</h1>
        <Fleuron />

        <div className="mt-6">
          <p className="dropcap" style={{ fontSize: 19, lineHeight: 1.65 }}>
            Saints Calendar is a research platform for the lives and feasts of the saints —
            an attempt to gather, into a single legible whole, two millennia of holiness:
            their biographies, their writings, the relics that survive them, the patronages
            tradition has assigned to them, and the calendars in which the Church has
            kept their memory.
          </p>
          <p style={{ fontSize: 18, lineHeight: 1.65, marginTop: 20 }}>
            Every entry is built from primary and scholarly sources, each cited at the foot of the saint's page.
            Where calendars disagree — Roman, Byzantine, Anglican, Coptic, Maronite — we record the divergence.
            Where the dates of birth and death are uncertain, we mark the uncertainty.
          </p>
          <p style={{ fontSize: 18, lineHeight: 1.65, marginTop: 20 }}>
            We are sister to <a href="https://nov3na.com" target="_blank" rel="noopener" style={{ color: "var(--gilt-deep)", borderBottom: "1px solid var(--gilt)" }}>Nov3na</a> —
            a platform for the praying of novenas. Each saint here links to the corresponding novena there.
          </p>
        </div>

        <div className="mt-8" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40 }}>
          <div>
            <div className="t-rubric mb-2">Editorial Principles</div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, fontSize: 15, lineHeight: 1.7 }}>
              <li>· Cite sources for every claim of fact</li>
              <li>· Distinguish hagiographical tradition from historical record</li>
              <li>· Honour the calendars of all apostolic Churches</li>
              <li>· Use original languages where possible</li>
              <li>· Render dates BC/AD; centuries in Roman numerals</li>
            </ul>
          </div>
          <div>
            <div className="t-rubric mb-2">Sources Consulted</div>
            <ul style={{ listStyle: "none", padding: 0, margin: 0, fontSize: 15, lineHeight: 1.7 }}>
              <li>· Acta Sanctorum (Bollandists)</li>
              <li>· Roman Martyrology, 2004 ed.</li>
              <li>· Butler's Lives of the Saints</li>
              <li>· The Oxford Dictionary of Saints</li>
              <li>· Bibliotheca Sanctorum (Lateran)</li>
              <li>· Synaxarion of Constantinople</li>
            </ul>
          </div>
        </div>

        <Fleuron />

        <div className="text-center t-meta mt-6">
          A.M.D.G. · Anno Domini MMXXVI
        </div>
      </div>
    </section>
  </div>
);

Object.assign(window, { SearchView, PatronageView, OrdersView, TimelineView, MapView, AboutView });
