// showcase.jsx — interactive tool showcase with category filter and detail expand

const { useState: useStateSC, useEffect: useEffectSC } = React;

function ToolShowcase() {
  const [cat, setCat] = useStateSC("All");
  const [active, setActive] = useStateSC(null);
  const tools = cat === "All" ? TOOLS : TOOLS.filter(t => t.cat === cat);

  return (
    <section id="tools">
      <div className="container">
        <div className="reveal"><div className="sec-label">04 / WORK</div></div>
        <div style={{display:"flex",justifyContent:"space-between",alignItems:"flex-end",gap:24,flexWrap:"wrap",marginBottom:36}}>
          <div>
            <h2 className="sec-title reveal" data-d="1" style={{marginBottom:14}}>
              <span style={{display:"block"}}>これまで作った、</span>
              <span style={{display:"block"}}><span style={{color:"var(--primary)"}}>"ちょっと面倒"</span> を畳むツールたち。</span>
            </h2>
            <p className="reveal sec-lead" data-d="2">
              業務用も生活用も、規模感の小さなものから運用に耐える業務システムまで。<br/>
              ジャンルで絞れます。気になるカードをクリックすると詳細が開きます。
            </p>
          </div>
        </div>

        {/* Category tabs */}
        <div className="reveal" data-d="2" style={{display:"flex",flexWrap:"wrap",gap:8,marginBottom:28}}>
          {CATS.map(c => {
            const sel = cat === c;
            return (
              <button key={c} onClick={()=>{setCat(c);setActive(null);}} style={{
                padding:"8px 16px",borderRadius:999,
                background: sel ? "var(--text)" : "transparent",
                color: sel ? "var(--bg)" : "var(--text-2)",
                border:"1px solid " + (sel ? "var(--text)" : "var(--line-2)"),
                fontFamily:"var(--mono)",fontSize:11.5,letterSpacing:"0.08em",fontWeight:600,
                cursor:"pointer",transition:"all .18s"
              }}>{c.toUpperCase()} <span style={{color:sel?"var(--muted)":"var(--muted)",marginLeft:4}}>{c==="All"?TOOLS.length:TOOLS.filter(t=>t.cat===c).length}</span></button>
            );
          })}
        </div>

        {/* Grid */}
        <style>{`
          @keyframes toolCardIn{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:none}}
          .tool-card-in{ animation: toolCardIn .45s cubic-bezier(.2,.7,.2,1) both }
        `}</style>
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(280px, 1fr))",gap:16}}>
          {tools.map((t, i) => (
            <ToolCard key={t.id} t={t} active={active===t.id} onClick={()=>setActive(active===t.id?null:t.id)} delay={i}/>
          ))}
        </div>

        {/* Active detail modal */}
        {active && (() => {
          const t = TOOLS.find(x => x.id === active);
          if (!t) return null;
          const accent = ACC[t.accent];
          return <ToolModal t={t} accent={accent} onClose={()=>setActive(null)}/>;
        })()}
      </div>
    </section>
  );
}

// Modal overlay for tool detail
function ToolModal({ t, accent, onClose }) {
  useEffectSC(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);

  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 200,
      background: "color-mix(in oklab, var(--bg) 60%, rgba(0,0,0,0.55))",
      backdropFilter: "blur(8px)", WebkitBackdropFilter: "blur(8px)",
      display: "grid", placeItems: "center",
      padding: "24px",
      animation: "tmFade .2s ease both"
    }}>
      <style>{`
        @keyframes tmFade{from{opacity:0}to{opacity:1}}
        @keyframes tmRise{from{opacity:0;transform:translateY(16px) scale(.98)}to{opacity:1;transform:none}}
      `}</style>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: "min(1040px, 100%)",
        maxHeight: "min(82vh, 720px)",
        background: "var(--surface)",
        border: "1px solid var(--line-2)",
        borderRadius: 22,
        boxShadow: "0 30px 80px rgba(11,14,19,0.18), 0 0 0 1px rgba(11,14,19,0.02)",
        position: "relative",
        overflow: "hidden",
        display: "flex",
        flexDirection: "column",
        animation: "tmRise .28s cubic-bezier(.2,.7,.2,1) both"
      }}>
        <button onClick={onClose} aria-label="閉じる" style={{
          position: "absolute", top: 16, right: 16, zIndex: 2,
          width: 38, height: 38, borderRadius: "50%",
          border: "1px solid var(--line-2)", background: "var(--surface)", color: "var(--text-2)",
          cursor: "pointer", display: "grid", placeItems: "center"
        }}><Icon name="x" size={16} stroke={2}/></button>

        <div style={{ overflow: "auto", flex: 1 }}>

        <div style={{ padding: "clamp(20px, 4vw, 40px)" }}>
          <div style={{ display: "grid", gridTemplateColumns: "1.35fr 1fr", gap: 36, alignItems: "start" }} className="detail-grid">
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
                <span style={{ padding: "4px 10px", borderRadius: 999, background: `color-mix(in oklab, ${accent} 18%, transparent)`, color: accent, fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.08em" }}>{t.cat.toUpperCase()}</span>
                <span style={{ fontFamily: "var(--mono)", fontSize: 11, color: "var(--muted)" }}>{t.en.toUpperCase()}</span>
              </div>
              <h3 style={{ margin: "0 0 18px", fontSize: "clamp(24px,2.4vw,32px)", fontWeight: 700, letterSpacing: "-0.02em" }}>{t.name}</h3>
              <p style={{ margin: "0 0 24px", color: "var(--text-2)", fontSize: "clamp(15px,1.2vw,17px)", lineHeight: 1.9 }}>{t.blurb}</p>
              <ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: 12 }}>
                {t.bullets.map((b, i) => (
                  <li key={i} style={{ display: "flex", alignItems: "flex-start", gap: 12, fontSize: 14.5 }}>
                    <span style={{ color: accent, marginTop: 3, flex: "none" }}><Icon name="check" size={16} stroke={2.4}/></span>
                    <span style={{ color: "var(--text-2)" }}>{b}</span>
                  </li>
                ))}
              </ul>
            </div>

            <div style={{
              background: "var(--bg)", border: "1px solid var(--line)", borderRadius: 18,
              padding: "26px 26px", position: "relative", overflow: "hidden"
            }}>
              <ToolPreview t={t} accent={accent}/>
            </div>
          </div>
          <style>{`@media (max-width:760px){.detail-grid{grid-template-columns:1fr !important}}`}</style>
        </div>
        </div>
      </div>
    </div>
  );
}
function ToolCard({ t, active, onClick, delay }) {
  const accent = ACC[t.accent];
  return (
    <button onClick={onClick} className="tool-card-in" style={{
      textAlign:"left",cursor:"pointer",
      background: active ? "var(--surface-2)" : "var(--surface)",
      border:`1px solid ${active ? "var(--line-2)" : "var(--line)"}`,
      borderRadius:16,padding:"22px 22px 24px",position:"relative",overflow:"hidden",
      transition:"background .2s, border-color .2s, transform .2s, box-shadow .2s",
      font:"inherit",color:"inherit",
      animationDelay: `${Math.min(5,(delay%6))*0.05}s`
    }}
    onMouseEnter={(e)=>{e.currentTarget.style.transform="translateY(-3px)";e.currentTarget.style.borderColor="var(--line-2)"}}
    onMouseLeave={(e)=>{e.currentTarget.style.transform="";e.currentTarget.style.borderColor=active?"var(--line-2)":"var(--line)"}}>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:18}}>
        <span style={{padding:"3px 9px",borderRadius:6,background:`color-mix(in oklab, ${accent} 16%, transparent)`,color:accent,fontFamily:"var(--mono)",fontSize:10.5,letterSpacing:"0.08em",fontWeight:600}}>{t.cat.toUpperCase()}</span>
        <span style={{width:24,height:24,borderRadius:"50%",background:active?accent:"transparent",border:`1px solid ${active?accent:"var(--line-2)"}`,display:"grid",placeItems:"center",color:active?"#0B0E13":"var(--text-2)",transition:"all .2s"}}>
          <Icon name={active?"minus":"plus"} size={12} stroke={2.4}/>
        </span>
      </div>
      <h3 style={{margin:"0 0 6px",fontSize:"clamp(16px,1.3vw,18px)",fontWeight:700,letterSpacing:"-0.005em"}}>{t.name}</h3>
      <div style={{fontFamily:"var(--mono)",fontSize:10.5,color:"var(--muted)",letterSpacing:"0.06em",marginBottom:14}}>{t.en}</div>
      <div style={{display:"flex",alignItems:"baseline",gap:10,paddingTop:12,borderTop:"1px solid var(--line)"}}>
        <span style={{fontFamily:"var(--display)",fontWeight:700,fontSize:20,color:accent,letterSpacing:"-0.01em"}}>{t.metric.v}</span>
        <span style={{fontSize:11.5,color:"var(--muted)"}}>{t.metric.k}</span>
      </div>
      <div style={{position:"absolute",right:-40,top:-40,width:120,height:120,borderRadius:"50%",background:accent,opacity:.06,filter:"blur(20px)",transition:"opacity .2s"}}/>
    </button>
  );
}

// Per-tool stylized preview (no fake screenshots — abstracted UI moments)
function ToolPreview({ t, accent }) {
  // a different mini-mock per tool id, falling back to a generic
  const mono = {fontFamily:"var(--mono)",fontSize:11.5,color:"var(--muted)",letterSpacing:"0.06em"};
  switch (t.id) {
    case "shipping":
      return (
        <div>
          <div style={mono}>SHIPPING SLIP / 2026.05.14</div>
          <div style={{marginTop:14,display:"grid",gridTemplateColumns:"1fr auto",gap:8}}>
            {[["市場A 出荷","142件"],["市場B 出荷","87件"],["返品処理","3件"]].map(([k,v],i)=>(
              <React.Fragment key={i}>
                <span style={{fontSize:13,color:"var(--text)"}}>{k}</span>
                <span style={{fontFamily:"var(--mono)",fontSize:13,color:accent}}>{v}</span>
              </React.Fragment>
            ))}
          </div>
          <div style={{marginTop:18,height:6,background:"var(--line)",borderRadius:3,overflow:"hidden"}}>
            <div style={{width:"100%",height:"100%",background:accent,animation:"shimmer 2.4s ease-in-out infinite",transformOrigin:"left"}}/>
          </div>
          <style>{`@keyframes shimmer{0%,100%{transform:scaleX(.4);opacity:.5}50%{transform:scaleX(1);opacity:1}}`}</style>
          <div style={{marginTop:10,fontSize:12,color:"var(--p-lime)"}}>✓ 232 件 / 印刷キュー送信完了</div>
        </div>
      );
    case "excel-dict":
    case "img-to-list":
      return (
        <div>
          <div style={mono}>{t.en.toUpperCase()}</div>
          <div style={{marginTop:14,display:"flex",alignItems:"center",gap:14}}>
            <div style={{flex:1,padding:14,border:"1px dashed var(--line-2)",borderRadius:10,textAlign:"center",fontFamily:"var(--mono)",fontSize:12,color:"var(--muted)"}}>raw.xlsx</div>
            <span style={{color:accent}}><Icon name="arrow" size={20}/></span>
            <div style={{flex:1,padding:14,border:`1px solid ${accent}`,borderRadius:10,textAlign:"center",fontFamily:"var(--mono)",fontSize:12,color:accent,background:`color-mix(in oklab, ${accent} 10%, transparent)`}}>output.xlsx</div>
          </div>
          <div style={{marginTop:18,fontSize:12.5,color:"var(--text-2)",lineHeight:1.7}}>
            <div>· 辞書ルール: <span style={{color:"var(--text)"}}>17 件</span></div>
            <div>· 処理レコード: <span style={{color:"var(--text)"}}>3,412 行</span></div>
            <div>· 経過: <span style={{color:accent}}>1.8 s</span></div>
          </div>
        </div>
      );
    case "streak":
      return (
        <div>
          <div style={mono}>STREAK · MAY</div>
          <div style={{fontFamily:"var(--display)",fontSize:48,fontWeight:700,lineHeight:1,marginTop:6,letterSpacing:"-0.02em"}}>27<span style={{color:"var(--muted)",fontSize:18,marginLeft:6}}>days</span></div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(14,1fr)",gap:4,marginTop:16}}>
            {Array.from({length:28}).map((_,i)=>(
              <span key={i} style={{aspectRatio:"1/1",borderRadius:4,background:i<24?accent:"var(--line)",opacity:i<24?(0.4+0.6*(i/24)):1}}/>
            ))}
          </div>
          <div style={{display:"flex",gap:6,marginTop:14}}>
            {["🥇","🔥","⭐"].map((e,i)=>(
              <span key={i} style={{width:28,height:28,borderRadius:"50%",background:"var(--surface-2)",border:"1px solid var(--line-2)",display:"grid",placeItems:"center",fontSize:13}}>{e}</span>
            ))}
          </div>
        </div>
      );
    case "newtab":
      return (
        <div>
          <div style={mono}>NEW TAB / WORK</div>
          <div style={{marginTop:14,display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:6}}>
            {["Drive","Sheets","Gmail","Slack","Notion","Cal","Stripe","GA","Figma"].map((l,i)=>(
              <div key={l} style={{padding:"10px 8px",border:"1px solid var(--line)",borderRadius:8,textAlign:"center",fontSize:11.5,color:"var(--text-2)",background:i%4===0?`color-mix(in oklab, ${accent} 14%, transparent)`:"transparent"}}>{l}</div>
            ))}
          </div>
        </div>
      );
    case "sns-viewer":
      return (
        <div>
          <div style={mono}>FEED · FILTERED</div>
          {[1,2,3].map(i=>(
            <div key={i} style={{marginTop:12,padding:"10px 12px",background:"var(--surface-2)",borderRadius:10,fontSize:12}}>
              <div style={{display:"flex",justifyContent:"space-between",color:"var(--muted)",fontSize:11,fontFamily:"var(--mono)"}}>
                <span>@user_{i}</span><span>2{i}m</span>
              </div>
              <div style={{marginTop:6,color:"var(--text-2)",lineHeight:1.5}}>
                {["業務改善のヒント。", "新しいツールを試した結果。", "今日のオペレーション進捗。"][i-1]}
              </div>
            </div>
          ))}
        </div>
      );
    case "course-site":
    case "members-msg":
      return (
        <div>
          <div style={mono}>{t.en.toUpperCase()}</div>
          <div style={{marginTop:14,display:"flex",flexDirection:"column",gap:8}}>
            {(t.id==="course-site"
              ? [["Chapter 01 · イントロ","✓"],["Chapter 02 · 基礎編","✓"],["Chapter 03 · 応用編","45%"],["Chapter 04 · 実践編","—"]]
              : [["田中 さん","2件の未読"],["山田 さん","既読"],["全体配信","12人着"]]
            ).map(([k,v],i)=>(
              <div key={i} style={{display:"flex",justifyContent:"space-between",padding:"10px 12px",background:"var(--surface-2)",borderRadius:8,fontSize:13}}>
                <span>{k}</span>
                <span style={{color:v==="✓"||v==="既読"?"var(--p-lime)":accent,fontFamily:"var(--mono)",fontSize:11.5}}>{v}</span>
              </div>
            ))}
          </div>
        </div>
      );
    case "house-task":
      return (
        <div>
          <div style={mono}>HOUSEHOLD · THIS WEEK</div>
          <div style={{marginTop:14,display:"flex",flexDirection:"column",gap:8}}>
            {[["皿洗い","パートナー A"],["ごみ出し","パートナー B"],["買い物","パートナー A"],["子供のお迎え","パートナー B"]].map(([k,v],i)=>(
              <div key={i} style={{display:"flex",alignItems:"center",gap:10,fontSize:13}}>
                <span style={{width:18,height:18,borderRadius:5,background:accent,display:"grid",placeItems:"center",color:"#0B0E13",flex:"none"}}><Icon name="check" size={12} stroke={3}/></span>
                <span style={{flex:1}}>{k}</span>
                <span style={{color:"var(--muted)",fontSize:11.5,fontFamily:"var(--mono)"}}>{v}</span>
              </div>
            ))}
          </div>
        </div>
      );
    case "split":
      return (
        <div>
          <div style={mono}>SPLIT · MAY</div>
          <div style={{display:"flex",alignItems:"baseline",gap:8,marginTop:8}}>
            <span style={{fontFamily:"var(--display)",fontSize:38,fontWeight:700,letterSpacing:"-0.02em"}}>¥ 12,840</span>
          </div>
          <div style={{fontSize:12,color:"var(--muted)",marginTop:4}}>A → B (50:50 折半 / 立替分差額)</div>
          <div style={{marginTop:16,display:"flex",height:10,borderRadius:5,overflow:"hidden",background:"var(--line)"}}>
            <div style={{width:"58%",background:accent}}/>
            <div style={{width:"42%",background:"var(--p-cyan)"}}/>
          </div>
          <div style={{display:"flex",justifyContent:"space-between",fontSize:11.5,marginTop:6,color:"var(--muted)",fontFamily:"var(--mono)"}}>
            <span>A 58%</span><span>B 42%</span>
          </div>
        </div>
      );
    case "pdf-edit":
    case "pdf-compress":
      return (
        <div>
          <div style={mono}>{t.id==="pdf-edit"?"PDF EDITOR":"PDF COMPRESS"}</div>
          {t.id==="pdf-compress" ? (
            <>
              <div style={{display:"flex",alignItems:"center",gap:10,marginTop:14}}>
                <span style={{fontFamily:"var(--display)",fontWeight:700,fontSize:26}}>12.4MB</span>
                <span style={{color:"var(--muted)"}}>→</span>
                <span style={{fontFamily:"var(--display)",fontWeight:700,fontSize:26,color:accent}}>1.1MB</span>
              </div>
              <div style={{marginTop:14,height:6,borderRadius:3,background:"var(--line)",overflow:"hidden"}}>
                <div style={{width:"91%",height:"100%",background:accent}}/>
              </div>
              <div style={{marginTop:6,fontSize:11.5,color:"var(--muted)",fontFamily:"var(--mono)"}}>SAVED 91%</div>
            </>
          ) : (
            <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:6,marginTop:14}}>
              {Array.from({length:8}).map((_,i)=>(
                <div key={i} style={{aspectRatio:"3/4",border:`1px solid ${i===2?accent:"var(--line-2)"}`,borderRadius:4,background:i===2?`color-mix(in oklab, ${accent} 12%, transparent)`:"transparent",position:"relative"}}>
                  <div style={{position:"absolute",bottom:4,left:4,fontFamily:"var(--mono)",fontSize:9,color:"var(--muted)"}}>p.{i+1}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      );
    default:
      return (
        <div>
          <div style={mono}>{t.en.toUpperCase()}</div>
          <div style={{marginTop:14,fontSize:13,color:"var(--text-2)",lineHeight:1.8}}>
            業務ヒアリングをもとに、必要十分な構成で実装した小〜中規模ツール。
          </div>
        </div>
      );
  }
}

Object.assign(window, { ToolShowcase });
