// portal-events.jsx — 告知ボード: DB(API)経由で催しの追加・削除・注目切替 + 画像アップロード + SNS共有

const API = "api.php";
const AUTH_API = "auth_api.php";

// API ヘルパ ───────────────────────────────────────────────
async function apiList() {
  const res = await fetch(API, { method: "GET", credentials: "same-origin" });
  if (!res.ok) throw new Error("list failed");
  const data = await res.json();
  return data.events || [];
}
async function apiCreate(form, imageFile) {
  const fd = new FormData();
  ["cat", "title", "date", "time", "place", "desc"].forEach(k => fd.append(k, form[k] || ""));
  if (imageFile) fd.append("image", imageFile);
  const res = await fetch(API, { method: "POST", body: fd, credentials: "same-origin" });
  const data = await res.json();
  if (!res.ok) throw new Error(data.error || "create failed");
  return data.event;
}
async function apiUpdate(id, patch) {
  const res = await fetch(API + "?id=" + id, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    credentials: "same-origin",
    body: JSON.stringify(patch)
  });
  const data = await res.json();
  if (!res.ok) throw new Error(data.error || "update failed");
  return data.event;
}
async function apiDelete(id) {
  const res = await fetch(API + "?id=" + id, { method: "DELETE", credentials: "same-origin" });
  if (!res.ok) {
    const data = await res.json().catch(() => ({}));
    throw new Error(data.error || "delete failed");
  }
  return true;
}

// 認証API ─────────────────────────────────────────────────
async function authStatus() {
  const res = await fetch(AUTH_API + "?action=status", { method: "GET", credentials: "same-origin" });
  if (!res.ok) return { loggedIn: false };
  return res.json();
}
async function authLogin(loginId, password) {
  const res = await fetch(AUTH_API + "?action=login", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "same-origin",
    body: JSON.stringify({ loginId, password })
  });
  const data = await res.json();
  if (!res.ok) throw new Error(data.error || "login failed");
  return data;
}
async function authLogout() {
  await fetch(AUTH_API + "?action=logout", { method: "POST", credentials: "same-origin" });
}

// SNS シェア ───────────────────────────────────────────────
function shareEvent(platform, ev, toast) {
  const text = `【安佐町のお知らせ】${ev.title}\n📅 ${ev.date}${ev.time ? " / " + ev.time : ""}\n📍 ${ev.place}\n${ev.desc || ""}`;
  const shareUrl = location.href.split("#")[0] + "#events";

  if (platform === "copy") {
    const full = text + "\n" + shareUrl + "\n#安佐町 #広島";
    if (navigator.clipboard) {
      navigator.clipboard.writeText(full).then(() => toast("コピーしました ─ SNSに貼り付けてください"));
    } else {
      toast("コピーしました");
    }
    return;
  }
  let url = "";
  if (platform === "x") {
    url = "https://twitter.com/intent/tweet?text=" + encodeURIComponent(text) +
          "&url=" + encodeURIComponent(shareUrl) + "&hashtags=" + encodeURIComponent("安佐町,広島,ASACHO");
  } else if (platform === "line") {
    url = "https://social-plugins.line.me/lineit/share?url=" + encodeURIComponent(shareUrl) +
          "&text=" + encodeURIComponent(text);
  } else if (platform === "fb") {
    url = "https://www.facebook.com/sharer/sharer.php?u=" + encodeURIComponent(shareUrl) +
          "&quote=" + encodeURIComponent(text);
  } else if (platform === "ig") {
    const cap = text + "\n#安佐町 #広島 #ASACHO";
    if (navigator.clipboard) navigator.clipboard.writeText(cap);
    toast("Instagram用キャプションをコピーしました");
    return;
  }
  if (url) {
    window.open(url, "_blank", "noopener,width=600,height=640");
    toast(platform.toUpperCase() + " のシェア画面を開きました");
  }
}

// カードのビジュアル ── 画像があれば写真、なければ抽象シーン
function EventVisual({ ev, onDelete, canEdit, onZoom }) {
  const c = catOf(ev.cat);
  const [imgOk, setImgOk] = React.useState(true);
  const showImg = ev.image && imgOk;

  // ev.image が変わったら読み込み状態をリセット
  React.useEffect(() => { setImgOk(true); }, [ev.image]);

  return (
    <div className="vis">
      {/* 画像が無い・読み込み失敗のときは常にこの背景を表示 */}
      <svg viewBox="0 0 400 250" preserveAspectRatio="xMidYMid slice">
        <defs>
          <linearGradient id={"evg-" + ev.id} x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor={c.color} stopOpacity=".9"/>
            <stop offset="100%" stopColor="#11160f" stopOpacity=".95"/>
          </linearGradient>
        </defs>
        <rect width="400" height="250" fill={"url(#evg-" + ev.id + ")"}/>
        <path d="M0,170 L70,130 L150,160 L230,120 L320,155 L400,125 L400,250 L0,250 Z" fill="#11160f" opacity=".5"/>
        <path d="M0,200 L90,165 L190,195 L290,165 L400,190 L400,250 L0,250 Z" fill="#0a0e0a" opacity=".7"/>
        <circle cx="320" cy="60" r="26" fill="#f3eee2" opacity=".22"/>
      </svg>
      {!showImg && <div className="glyph">{c.glyph}</div>}

      {showImg && (
        <img src={ev.image} alt={ev.title}
             loading="lazy" decoding="async"
             onClick={() => onZoom(ev.image, ev.title)}
             onError={() => setImgOk(false)}
             style={{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover",cursor:"zoom-in",zIndex:1}} />
      )}

      <div className="cat"><span className="dot" style={{background:c.color}}></span>{c.ja} · {c.en}</div>
      {canEdit && <button className="del" onClick={() => onDelete(ev.id)} title="削除">×</button>}
    </div>
  );
}

function EventCard({ ev, onDelete, onTogglePin, toast, canEdit, onZoom }) {
  const isNew = (Date.now() - (ev.createdAt || 0)) < 1000 * 60 * 60 * 24 * 14;
  const [expanded, setExpanded] = React.useState(false);
  const [overflowing, setOverflowing] = React.useState(false);
  const descRef = React.useRef(null);

  // 折りたたみ時に7行を超えているか判定（ボタンの表示要否）
  React.useEffect(() => {
    const el = descRef.current;
    if (!el) return;
    const check = () => {
      if (expanded) return; // 展開中は判定しない
      // scrollHeight が clientHeight より大きければ省略されている
      setOverflowing(el.scrollHeight - el.clientHeight > 2);
    };
    check();
    window.addEventListener("resize", check);
    return () => window.removeEventListener("resize", check);
  }, [ev.desc, expanded]);

  return (
    <article className="ev-card reveal">
      <EventVisual ev={ev} onDelete={onDelete} canEdit={canEdit} onZoom={onZoom} />
      <div className="body">
        <div className="date">
          {canEdit ? (
            <button
              onClick={() => onTogglePin(ev)}
              title={ev.pinned ? "注目を解除" : "注目に設定"}
              style={{padding:"2px 7px",borderRadius:3,fontSize:"8.5px",letterSpacing:".14em",
                background: ev.pinned ? "var(--gold)" : "transparent",
                color: ev.pinned ? "var(--paper)" : "var(--t-ink-3)",
                border: ev.pinned ? "none" : ".5px solid var(--line-l)"}}>
              {ev.pinned ? "注目" : "＋注目"}
            </button>
          ) : (
            ev.pinned && <span className="new" style={{background:"var(--gold)"}}>注目</span>
          )}
          {isNew && !ev.pinned && <span className="new">NEW</span>}
          {ev.date}{ev.time ? <span style={{color:"var(--t-ink-3)"}}>· {ev.time}</span> : null}
        </div>
        <h3>{ev.title}</h3>
        <div className="place">◉ {ev.place}</div>
        <p ref={descRef} className={"desc" + (expanded ? " expanded" : " clamp")}>{ev.desc}</p>
        {(overflowing || expanded) && (
          <button className="desc-toggle" onClick={() => setExpanded(v => !v)}>
            {expanded ? "閉じる ▲" : "詳しく見る ▼"}
          </button>
        )}
      </div>
      <div className="foot">
        <span className="share-lbl">SNSで広める</span>
        <div className="ev-share">
          <button className="x" title="Xでシェア" onClick={() => shareEvent("x", ev, toast)}><IconX/></button>
          <button className="fb" title="Facebookでシェア" onClick={() => shareEvent("fb", ev, toast)}><IconFB/></button>
          <button className="ig" title="Instagram用にコピー" onClick={() => shareEvent("ig", ev, toast)}><IconIG/></button>
          <button className="copy" title="本文をコピー" onClick={() => shareEvent("copy", ev, toast)}><IconCopy/></button>
        </div>
      </div>
    </article>
  );
}

// 画像ライトボックス（拡大表示）
function Lightbox({ src, alt, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    if (src) {
      document.addEventListener("keydown", onKey);
      document.body.style.overflow = "hidden";
    }
    return () => { document.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [src, onClose]);

  if (!src) return null;
  return (
    <div onClick={onClose}
      style={{position:"fixed",inset:0,zIndex:400,background:"rgba(8,10,8,.92)",
        backdropFilter:"blur(8px)",display:"grid",placeItems:"center",padding:32,cursor:"zoom-out"}}>
      <button onClick={onClose}
        style={{position:"absolute",right:24,top:24,width:44,height:44,borderRadius:"50%",
          border:".5px solid rgba(243,238,226,.4)",color:"var(--paper)",fontSize:22,
          display:"grid",placeItems:"center"}}>×</button>
      <figure onClick={e => e.stopPropagation()}
        style={{margin:0,maxWidth:"100%",maxHeight:"100%",display:"flex",flexDirection:"column",
          alignItems:"center",gap:16,cursor:"default"}}>
        <img src={src} alt={alt}
          style={{maxWidth:"100%",maxHeight:"82vh",objectFit:"contain",borderRadius:6,
            boxShadow:"0 40px 100px -30px rgba(0,0,0,.8)"}} />
        {alt && <figcaption style={{color:"rgba(243,238,226,.8)",fontFamily:"var(--f-min)",fontSize:15,
          letterSpacing:".02em",textAlign:"center"}}>{alt}</figcaption>}
      </figure>
    </div>
  );
}

// ログイン画面（モーダル）
function LoginModal({ open, onClose, onSuccess }) {
  const [loginId, setLoginId] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [show, setShow] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");

  React.useEffect(() => {
    if (open) { setLoginId(""); setPassword(""); setShow(false); setBusy(false); setErr(""); }
  }, [open]);

  const submit = async () => {
    if (busy) return;
    if (!loginId.trim() || !password) { setErr("ログインIDとパスワードを入力してください"); return; }
    setBusy(true); setErr("");
    try {
      const data = await authLogin(loginId.trim(), password);
      onSuccess(data);
    } catch (e) {
      setErr(e.message);
      setBusy(false);
    }
  };

  return (
    <div className={"modal-bg" + (open ? " open" : "")} onClick={onClose}>
      <div className="modal" style={{width:"min(440px,100%)"}} onClick={e => e.stopPropagation()}>
        <div className="mh">
          <div>
            <div className="k">MEMBER LOGIN</div>
            <h3>ログイン</h3>
          </div>
          <button className="x" onClick={onClose}>×</button>
        </div>
        <div className="mb">
          <p style={{fontSize:13,lineHeight:1.8,color:"var(--t-ink-3)",marginTop:-4}}>
            催しの追加・編集にはログインが必要です。
          </p>
          <div className="field">
            <label>ログインID</label>
            <input value={loginId} autoFocus onChange={e => setLoginId(e.target.value)}
              onKeyDown={e => e.key === "Enter" && submit()} placeholder="ログインID" />
          </div>
          <div className="field">
            <label>パスワード</label>
            <div style={{position:"relative"}}>
              <input type={show ? "text" : "password"} value={password}
                onChange={e => setPassword(e.target.value)}
                onKeyDown={e => e.key === "Enter" && submit()}
                placeholder="パスワード" style={{width:"100%",paddingRight:54}} />
              <button onClick={() => setShow(s => !s)}
                style={{position:"absolute",right:8,top:"50%",transform:"translateY(-50%)",
                  fontFamily:"var(--f-mono)",fontSize:10,letterSpacing:".1em",color:"var(--t-ink-3)",
                  padding:"6px 8px"}}>{show ? "隠す" : "表示"}</button>
            </div>
          </div>
          {err && <div style={{color:"var(--vermillion)",fontSize:12.5,letterSpacing:".02em"}}>{err}</div>}
          <div className="mfoot">
            <button className="btn-ghost" onClick={onClose} disabled={busy}>キャンセル</button>
            <button className="btn-solid" onClick={submit} disabled={busy}>
              {busy ? "確認中…" : "ログイン →"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

const BLANK = { cat: "notice", title: "", date: "", time: "", place: "", desc: "" };

function AddEventModal({ open, onClose, onAdd }) {
  const [form, setForm] = React.useState(BLANK);
  const [imageFile, setImageFile] = React.useState(null);
  const [preview, setPreview] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const fileRef = React.useRef(null);

  React.useEffect(() => {
    if (open) { setForm(BLANK); setImageFile(null); setPreview(""); setBusy(false); }
  }, [open]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const valid = form.title.trim() && form.date.trim() && form.place.trim();

  const pickImage = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    if (file.size > 15 * 1024 * 1024) { alert("画像サイズは15MB以下にしてください"); return; }
    setImageFile(file);
    const reader = new FileReader();
    reader.onload = () => setPreview(reader.result);
    reader.readAsDataURL(file);
  };
  const clearImage = () => {
    setImageFile(null); setPreview("");
    if (fileRef.current) fileRef.current.value = "";
  };

  const submit = async () => {
    if (!valid || busy) return;
    setBusy(true);
    try {
      await onAdd(form, imageFile);
      onClose();
    } catch (err) {
      alert("追加に失敗しました: " + err.message);
      setBusy(false);
    }
  };

  return (
    <div className={"modal-bg" + (open ? " open" : "")} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="mh">
          <div>
            <div className="k">NEW ANNOUNCEMENT</div>
            <h3>催しを追加</h3>
          </div>
          <button className="x" onClick={onClose}>×</button>
        </div>
        <div className="mb">
          <div className="field">
            <label>カテゴリ</label>
            <div className="cat-picker">
              {CATEGORIES.map(c => (
                <div key={c.id} className={"opt" + (form.cat === c.id ? " on" : "")}
                  style={form.cat === c.id ? { background: c.color } : {}}
                  onClick={() => set("cat", c.id)}>
                  <span className="sw" style={{ background: form.cat === c.id ? "var(--paper)" : c.color }}></span>
                  {c.ja}
                </div>
              ))}
            </div>
          </div>

          <div className="field">
            <label>催し名 <span className="req">必須</span></label>
            <input value={form.title} onChange={e => set("title", e.target.value)} placeholder="例：親子でミニマルシェ" />
          </div>

          <div className="field row2">
            <div className="field">
              <label>日付 <span className="req">必須</span></label>
              <input value={form.date} onChange={e => set("date", e.target.value)} placeholder="例：2026.06.28" />
            </div>
            <div className="field">
              <label>時間</label>
              <input value={form.time} onChange={e => set("time", e.target.value)} placeholder="例：10:00 — 14:00" />
            </div>
          </div>

          <div className="field">
            <label>場所 <span className="req">必須</span></label>
            <input value={form.place} onChange={e => set("place", e.target.value)} placeholder="例：飯室駅前ひろば" />
          </div>

          <div className="field">
            <label>内容</label>
            <textarea value={form.desc} onChange={e => set("desc", e.target.value)} placeholder="催しの詳細、対象、参加方法などを入力してください。" />
          </div>

          {/* 画像アップロード */}
          <div className="field">
            <label>催しの画像 <span style={{color:"var(--t-ink-3)"}}>JPEG / PNG / GIF / WebP（iPhoneのHEICも可）・15MBまで</span></label>
            <input ref={fileRef} type="file" accept="image/*" onChange={pickImage}
              style={{padding:"10px 12px"}} />
            {preview && (
              <div style={{position:"relative",marginTop:10,borderRadius:6,overflow:"hidden",border:".5px solid var(--line-l)"}}>
                <img src={preview} alt="プレビュー" style={{width:"100%",maxHeight:220,objectFit:"cover",display:"block"}} />
                <button onClick={clearImage}
                  style={{position:"absolute",right:10,top:10,width:30,height:30,borderRadius:"50%",
                    background:"rgba(10,14,10,.7)",color:"var(--paper)",display:"grid",placeItems:"center",fontSize:16}}>×</button>
              </div>
            )}
          </div>

          <div className="mfoot">
            <button className="btn-ghost" onClick={onClose} disabled={busy}>キャンセル</button>
            <button className="btn-solid" disabled={!valid || busy} onClick={submit}>
              {busy ? "送信中…" : "追加して掲載 →"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function EventsSection({ toast }) {
  const [events, setEvents] = React.useState([]);
  const [filter, setFilter] = React.useState("all");
  const [modal, setModal] = React.useState(false);
  const [loginOpen, setLoginOpen] = React.useState(false);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState("");
  const [admin, setAdmin] = React.useState(null);   // ログイン中のID（未ログインなら null）
  const [role, setRole] = React.useState(null);      // admin / editor / poster
  const [canManageMembers, setCanManageMembers] = React.useState(false);
  const [zoom, setZoom] = React.useState(null);      // { src, alt } | null

  const loggedIn = !!admin;   // ログインしていれば投稿は可能

  const roleLabel = (r) => r === "admin" ? "管理者" : r === "editor" ? "編集者" : r === "poster" ? "投稿者" : "";

  const refresh = React.useCallback(async () => {
    try {
      setLoading(true);
      const list = await apiList();
      setEvents(list);
      setError("");
    } catch (e) {
      setError("催し物の読み込みに失敗しました。サーバーとデータベースの設定をご確認ください。");
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => {
    refresh();
    authStatus().then(s => {
      if (s.loggedIn) {
        setAdmin(s.loginId || "user");
        setRole(s.role || null);
        setCanManageMembers(!!s.canManageMembers);
      }
    }).catch(() => {});
  }, [refresh]);

  // ログインが必要な操作を実行（未ログインならログイン画面へ）
  const requireAuth = (fn) => {
    if (loggedIn) { fn(); } else { setLoginOpen(true); }
  };

  const onLoginSuccess = (info) => {
    setAdmin((info && info.loginId) || "user");
    setRole((info && info.role) || null);
    setCanManageMembers(!!(info && info.canManageMembers));
    setLoginOpen(false);
    toast("ログインしました");
  };

  const logout = async () => {
    await authLogout();
    setAdmin(null); setRole(null); setCanManageMembers(false);
    toast("ログアウトしました");
  };

  const addEvent = async (form, imageFile) => {
    const ev = await apiCreate(form, imageFile);
    setEvents(list => [ev, ...list]);
    toast("催しを掲載しました");
  };

  const delEvent = async (id) => {
    if (!loggedIn) { setLoginOpen(true); return; }
    if (!confirm("この催しを削除しますか？")) return;
    try {
      await apiDelete(id);
      setEvents(list => list.filter(e => e.id !== id));
      toast("削除しました");
    } catch (e) {
      if (/ログイン/.test(e.message)) { setAdmin(null); setLoginOpen(true); }
      else alert("削除に失敗しました: " + e.message);
    }
  };

  const togglePin = async (ev) => {
    if (!loggedIn) { setLoginOpen(true); return; }
    try {
      const updated = await apiUpdate(ev.id, { pinned: !ev.pinned });
      setEvents(list => list.map(e => e.id === updated.id ? updated : e));
    } catch (e) {
      if (/ログイン/.test(e.message)) { setAdmin(null); setLoginOpen(true); }
      else alert("更新に失敗しました: " + e.message);
    }
  };

  const counts = {};
  events.forEach(e => { counts[e.cat] = (counts[e.cat] || 0) + 1; });

  const shown = events
    .filter(e => filter === "all" || e.cat === filter)
    .sort((a, b) => (b.pinned ? 1 : 0) - (a.pinned ? 1 : 0));

  return (
    <section className="events" id="events">
      <div className="wrap">
        <div className="sec-head reveal">
          <div className="l">
            <div className="num">01 ─ ANNOUNCEMENTS</div>
            <h2>お知らせ・催し<span className="en">Events &amp; Notices</span></h2>
          </div>
          <div className="r">
            安佐町でひらかれる催しを掲載する掲示板。催しはデータベースに保存され、画像も掲載できます（画像はクリックで拡大表示）。各カードからX・FacebookなどSNSへ発信できます。催しの追加・編集にはログインが必要です（権限により編集範囲が異なります）。
          </div>
        </div>

        <div className="ev-toolbar reveal">
          <div className="ev-filters">
            <button className={"fil" + (filter === "all" ? " on" : "")} onClick={() => setFilter("all")}>
              すべて <span className="ct">{events.length}</span>
            </button>
            {CATEGORIES.filter(c => counts[c.id]).map(c => (
              <button key={c.id} className={"fil" + (filter === c.id ? " on" : "")} onClick={() => setFilter(c.id)}>
                <span style={{ width: 8, height: 8, borderRadius: "50%", background: c.color, display: "inline-block" }}></span>
                {c.ja} <span className="ct">{counts[c.id]}</span>
              </button>
            ))}
          </div>
          <div style={{display:"flex",gap:10,alignItems:"center"}}>
            {loggedIn ? (
              <>
                <span style={{fontFamily:"var(--f-mono)",fontSize:10.5,letterSpacing:".06em",color:"var(--t-ink-3)"}}>
                  {admin}（{roleLabel(role)}）
                </span>
                <button className="ev-add" onClick={() => setModal(true)}>
                  <span className="ic">＋</span> 催しを追加
                </button>
                {canManageMembers && (
                  <a className="btn-ghost" href="admin.html" style={{padding:"9px 16px",fontSize:12,textDecoration:"none"}}>
                    メンバー設定
                  </a>
                )}
                <button className="btn-ghost" style={{padding:"9px 16px",fontSize:12}} onClick={logout}>
                  ログアウト
                </button>
              </>
            ) : (
              <button className="ev-add" onClick={() => setLoginOpen(true)}>
                <span className="ic">🔒</span> ログイン
              </button>
            )}
          </div>
        </div>

        <div className="ev-grid">
          {loading && <div className="ev-empty">読み込み中…</div>}
          {!loading && error && <div className="ev-empty">{error}</div>}
          {!loading && !error && shown.length === 0 && (
            <div className="ev-empty">このカテゴリの催しはまだありません。{loggedIn && <><br/>「＋ 催しを追加」から掲載できます。</>}</div>
          )}
          {!loading && !error && shown.map(ev => (
            <EventCard key={ev.id} ev={ev} onDelete={delEvent} onTogglePin={togglePin}
              toast={toast} canEdit={!!ev.canEdit} onZoom={(src, alt) => setZoom({ src, alt })} />
          ))}
        </div>

        <div className="sns-banner reveal">
          <div className="l">
            <div className="k">FOLLOW US ─ 公式SNS</div>
            <h3>安佐町の「いま」を、<br/>毎日お届けしています。</h3>
            <p>掲載された催しは公式アカウントでも発信中。フォローして、里山の四季と暮らしの情報を受け取ってください。</p>
          </div>
          <div className="accounts">
            <a className="acc" href="https://x.com/asacho_machiko" target="_blank" rel="noopener noreferrer">
              <IconX/><div className="h"><b>X</b><span>@asacho_machiko</span></div>
            </a>
            <a className="acc" href="https://www.instagram.com/asa_cho.hiroshima/" target="_blank" rel="noopener noreferrer">
              <IconIG/><div className="h"><b>Instagram</b><span>@asa_cho.hiroshima</span></div>
            </a>
            <a className="acc" href="https://www.facebook.com/asachofm" target="_blank" rel="noopener noreferrer">
              <IconFB/><div className="h"><b>Facebook</b><span>asachofm</span></div>
            </a>
            <a className="acc" href="#" onClick={e=>e.preventDefault()}>
              <IconYT/><div className="h"><b>YouTube</b><span>Asa-cho Channel</span></div>
            </a>
          </div>
        </div>
      </div>

      <AddEventModal open={modal} onClose={() => setModal(false)} onAdd={addEvent} />
      <LoginModal open={loginOpen} onClose={() => setLoginOpen(false)} onSuccess={onLoginSuccess} />
      <Lightbox src={zoom && zoom.src} alt={zoom && zoom.alt} onClose={() => setZoom(null)} />
    </section>
  );
}

Object.assign(window, { EventsSection });
