/* global React */
const { useState, useEffect } = React;

const COLUMN_CATS = ["All", "Insight", "News", "Notice", "Event"];

function Column() {
  const [active, setActive] = useState("All");
  const [posts, setPosts] = useState([]);
  const [showAll, setShowAll] = useState(false);

  useEffect(() => {
    fetch("posts/index.json")
      .then((r) => r.json())
      .then(setPosts)
      .catch(() => setPosts([]));
  }, []);

  // Resolve href for a post:
  //  - external link → open in new tab
  //  - otherwise   → dedicated static page at /column/<id>/
  const postHref = (p) => p.link || `/column/${p.id}/`;
  const isExternal = (p) => !!p.link;

  // Reset show-all when filter changes
  useEffect(() => { setShowAll(false); }, [active]);

  const visible = active === "All" ? posts : posts.filter((p) => p.category === active);
  const [feature, ...rest] = visible;
  // Limit to 6 cards (so feature + 6 = 7 total) unless expanded
  const VISIBLE_CARDS = 6;
  const restVisible = showAll ? rest : rest.slice(0, VISIBLE_CARDS);
  const hasMore = rest.length > VISIBLE_CARDS;

  return (
    <section id="column" className="column section section--paper" data-screen-label="10 Column">
      <div className="container">
        <div className="column__head reveal">
          <div>
            <span className="eyebrow">Insights & Notice</span>
            <h2 className="column__title heading-jp">コラム<em>&</em>お知らせ</h2>
          </div>
          <p className="column__lede body-jp">
            企業法務の実務知見、改正法のアップデート、メディア掲載やイベント情報——<br/>
            LegalAgentから定期的に発信しています
          </p>
        </div>

        <div className="column__filter reveal">
          {COLUMN_CATS.map((c) => (
            <button
              key={c}
              type="button"
              className={`column__filter-btn ${active === c ? "is-active" : ""}`}
              onClick={() => setActive(c)}
            >
              {c}
              <span className="column__filter-count">
                {c === "All" ? posts.length : posts.filter((p) => p.category === c).length}
              </span>
            </button>
          ))}
        </div>

        {feature && (
          <a
            href={postHref(feature)}
            target={isExternal(feature) ? "_blank" : undefined}
            rel={isExternal(feature) ? "noopener noreferrer" : undefined}
            className="column__feature lift"
            key={feature.id}
          >
            <div className="column__feature-meta">
              <span className="column__cat" data-cat={feature.category}>{feature.category}</span>
              <span className="column__date">{feature.date}</span>
              <span className="column__read">{feature.readMin}</span>
            </div>
            <h3 className="column__feature-title heading-jp">{feature.title}</h3>
            <p className="column__feature-excerpt body-jp">{feature.excerpt}</p>
            <span className="column__feature-cta">
              {isExternal(feature) ? "外部リンクを開く" : "続きを読む"}
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                {isExternal(feature)
                  ? <path d="M3 11l8-8M5 3h6v6" stroke="currentColor" strokeWidth="1.2"/>
                  : <path d="M2 7h10M7 2l5 5-5 5" stroke="currentColor" strokeWidth="1"/>}
              </svg>
            </span>
          </a>
        )}

        <div className="column__grid">
          {restVisible.map((p, i) => (
            <a
              href={postHref(p)}
              target={isExternal(p) ? "_blank" : undefined}
              rel={isExternal(p) ? "noopener noreferrer" : undefined}
              key={p.id}
              className="column__card lift"
              style={{transitionDelay: `${0.05 * i}s`}}
            >
              <div className="column__card-meta">
                <span className="column__cat" data-cat={p.category}>{p.category}</span>
                <span className="column__date">{p.date}</span>
              </div>
              <h3 className="column__card-title heading-jp">{p.title}</h3>
              <p className="column__card-excerpt body-jp">{p.excerpt}</p>
              <span className="column__card-foot">
                <span className="column__read">{p.readMin}</span>
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                  {isExternal(p)
                    ? <path d="M3 11l8-8M5 3h6v6" stroke="currentColor" strokeWidth="1.2"/>
                    : <path d="M2 7h10M7 2l5 5-5 5" stroke="currentColor" strokeWidth="1"/>}
                </svg>
              </span>
            </a>
          ))}
        </div>

        {hasMore && (
          <div className="column__more">
            <button type="button" className="column__more-btn" onClick={() => setShowAll((v) => !v)}>
              {showAll ? "閉じる" : `もっと見る（あと ${rest.length - VISIBLE_CARDS} 件）`}
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ transform: showAll ? "rotate(180deg)" : "none", transition: "transform 0.3s ease" }}>
                <path d="M3 5l4 4 4-4" stroke="currentColor" strokeWidth="1.2" />
              </svg>
            </button>
          </div>
        )}

        {posts.length === 0 && (
          <p className="column__empty body-jp">記事を読み込み中、または posts/index.json が見つかりません</p>
        )}
      </div>

    </section>
  );
}

window.Column = Column;
