/* Components 2 — Skills, Experience, Github graph, Writing, Now, Contact, CmdK */
const { useState: useStateB, useEffect: useEffectB, useRef: useRefB, useMemo: useMemoB } = React;

/* ---------- Skills ---------- */

function Skills({ lang }) {
  const T = window.I18N[lang];
  const cats = window.PORTFOLIO_DATA.skillCategories;
  const [active, setActive] = useStateB(cats[0].key);
  const cur = cats.find((c) => c.key === active);
  return (
    <section className="section" id="skills">
      <div className="shell">
        <SectionHead idx="03" cmd={T.skills_cmd} title={T.skills_title} count={T.skills_count(cats.length)} />
        <div className="skills">
          <div className="skills-cat-list">
            {cats.map((c, i) => (
              <div
                key={c.key}
                className={"skills-cat" + (active === c.key ? " active" : "")}
                onClick={() => setActive(c.key)}
              >
                <span>{String(i+1).padStart(2,"0")}. {lang === "de" && c.label_de ? c.label_de : c.label}</span>
                <span className="num">{c.count}</span>
              </div>
            ))}
          </div>
          <div className="skills-pane">
            <div className="skills-pane-head">
              <h3>{lang === "de" && cur.label_de ? cur.label_de : cur.label}</h3>
              <span className="meta">{T.skills_tools(cur.items.length)}</span>
            </div>
            <div className="skills-grid">
              {cur.items.map((s) => (
                <div className="skill" key={s.name}>
                  <span>{lang === "de" && s.name_de ? s.name_de : s.name}</span>
                  <span className="lvl">
                    {[1,2,3,4,5].map((n) => (
                      <span key={n} className={n <= s.lvl ? "on" : ""}></span>
                    ))}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Experience timeline ---------- */

function Experience({ lang }) {
  const T = window.I18N[lang];
  const tl = window.PORTFOLIO_DATA.timeline;
  return (
    <section className="section" id="experience">
      <div className="shell">
        <SectionHead idx="04" cmd={T.exp_cmd} title={T.exp_title} count={T.exp_count(tl.length)} />
        <div className="timeline">
          {tl.map((row, i) => (
            <div key={i} className={"tl-row" + (row.now ? " now" : "")}>
              <div className="tl-year">
                {row.year}
                {row.now && <span style={{ color: "var(--accent)", marginLeft: 8 }}>{T.exp_now_label}</span>}
              </div>
              <div>
                <div className="tl-title">{lang === "de" && row.title_de ? row.title_de : row.title}</div>
                <div className="tl-org">{lang === "de" && row.org_de ? row.org_de : row.org}</div>
                <div className="tl-desc">{lang === "de" && row.desc_de ? row.desc_de : row.desc}</div>
                <div className="tl-tags">
                  {row.tags.map((t) => (<span key={t} className="tl-tag">{t}</span>))}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- GitHub Graph ---------- */

const TOTAL_WEEKS = 53;

function useIsMobile(bp) {
  const [mobile, setMobile] = useStateB(() => typeof window !== "undefined" && window.innerWidth <= bp);
  useEffectB(() => {
    const h = () => setMobile(window.innerWidth <= bp);
    window.addEventListener("resize", h);
    return () => window.removeEventListener("resize", h);
  }, [bp]);
  return mobile;
}

function GithubGraph({ lang }) {
  const T = window.I18N[lang];
  const isMobile = useIsMobile(600);

  // Generate all 53 weeks deterministically
  const allCells = useMemoB(() => {
    const out = [];
    let seed = 42;
    const rnd = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; };
    for (let w = 0; w < TOTAL_WEEKS; w++) {
      for (let d = 0; d < 7; d++) {
        const recency = w / TOTAL_WEEKS;
        const weekdayBoost = (d > 0 && d < 6) ? 0.25 : 0;
        const score = rnd() * (0.4 + recency * 0.6) + weekdayBoost;
        let lvl = 0;
        if (score > 0.85) lvl = 4;
        else if (score > 0.65) lvl = 3;
        else if (score > 0.45) lvl = 2;
        else if (score > 0.25) lvl = 1;
        if (rnd() < 0.08) lvl = 0;
        out.push({ w, d, lvl });
      }
    }
    return out;
  }, []);

  const total = allCells.reduce((a, c) => a + c.lvl * 3 + (c.lvl > 0 ? 1 : 0), 0);

  // Mobile: show last 26 weeks with smaller cells
  const displayWeeks = isMobile ? 26 : TOTAL_WEEKS;
  const wOffset = TOTAL_WEEKS - displayWeeks;
  const cells = allCells.filter(c => c.w >= wOffset);

  const cell = isMobile ? 11 : 13;
  const gap  = isMobile ? 2  : 3;
  const labelW = isMobile ? 22 : 30;
  const labelTopH = isMobile ? 14 : 16;
  const monthFontSize = isMobile ? "9"  : "10";
  const dayFontSize   = isMobile ? "8"  : "9";

  const W = displayWeeks * (cell + gap);
  const H = 7 * (cell + gap);
  const svgW = W + labelW;
  const svgH = H + (isMobile ? 18 : 24);

  // Months: on mobile show last 6 (one label per ~4 weeks)
  const allMonths = T.gh_months;
  const months = isMobile ? allMonths.slice(6) : allMonths;
  const monthStep = W / months.length;

  const ghDays = T.gh_days;

  return (
    <section className="section" id="github">
      <div className="shell">
        <SectionHead idx="05" cmd={T.gh_cmd} title={T.gh_title} count={T.gh_count(total)} />
        <div className="gh-grid">
          <div>
            <div className="gh-graph">
              <svg
                width={svgW}
                height={svgH}
                viewBox={`0 0 ${svgW} ${svgH}`}
                style={{ maxWidth: "100%", display: "block" }}
              >
                {months.map((m, i) => (
                  <text
                    key={m}
                    x={labelW + i * monthStep}
                    y="10"
                    fill="var(--fg-dim)"
                    fontFamily="var(--mono)"
                    fontSize={monthFontSize}
                    letterSpacing="0.06em"
                  >{m}</text>
                ))}
                {ghDays.map((d, i) => (
                  <text
                    key={d}
                    x="0"
                    y={(isMobile ? 22 : 26) + (i * 2 + 1) * (cell + gap)}
                    fill="var(--fg-dim)"
                    fontFamily="var(--mono)"
                    fontSize={dayFontSize}
                    letterSpacing="0.06em"
                  >{d}</text>
                ))}
                <g transform={`translate(${labelW}, ${labelTopH})`}>
                  {cells.map((c, i) => (
                    <rect
                      key={i}
                      x={(c.w - wOffset) * (cell + gap)}
                      y={c.d * (cell + gap)}
                      width={cell}
                      height={cell}
                      className={c.lvl === 0 ? "gh-cell-bg" : `gh-cell l${c.lvl}`}
                      rx="1"
                    >
                      <title>{c.lvl} contributions</title>
                    </rect>
                  ))}
                </g>
              </svg>
            </div>
            <div className="gh-legend">
              <span>{T.gh_less}</span>
              <span className="scale">
                <span style={{ background: "rgba(255,255,255,0.05)" }}></span>
                <span style={{ background: "color-mix(in oklab, var(--accent) 30%, var(--fg-mute))" }}></span>
                <span style={{ background: "color-mix(in oklab, var(--accent) 55%, var(--fg-mute))" }}></span>
                <span style={{ background: "color-mix(in oklab, var(--accent) 80%, var(--fg-mute))" }}></span>
                <span style={{ background: "var(--accent)" }}></span>
              </span>
              <span>{T.gh_more}</span>
              {!isMobile && <span style={{ marginLeft: "auto" }}>{T.gh_handle}</span>}
            </div>
          </div>

          <div className="gh-stats">
            <div className="row"><span className="k">{T.gh_pub_repos}</span><span className="v acc">42</span></div>
            <div className="row"><span className="k">{T.gh_contributions_key}</span><span className="v">{total}</span></div>
            <div className="row"><span className="k">{T.gh_longest}</span><span className="v">{T.gh_days_val}</span></div>
            <div className="row"><span className="k">{T.gh_current}</span><span className="v acc">{T.gh_streak_val}</span></div>
            <div className="row"><span className="k">{T.gh_active}</span><span className="v">PHP</span></div>
            <div className="row"><span className="k">{T.gh_first}</span><span className="v">2013</span></div>
            <div className="row"><span className="k">{T.gh_followers}</span><span className="v">—</span></div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Writing ---------- */

function Writing({ lang }) {
  const T = window.I18N[lang];
  const posts = window.PORTFOLIO_DATA.writing;
  return (
    <section className="section" id="writing">
      <div className="shell">
        <SectionHead idx="06" cmd={T.writing_cmd} title={T.writing_title} count={T.writing_count(posts.length)} />
        <div className="writing-list">
          {posts.map((p, i) => (
            <a key={i} className="write" href="#">
              <span className="write-date">{p.date}</span>
              <span className="write-title">{lang === "de" && p.title_de ? p.title_de : p.title}</span>
              <span className="write-cat">{lang === "de" && p.cat_de ? p.cat_de : p.cat}</span>
              <span className="write-arr">→</span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ---------- Now ---------- */

function Now({ lang }) {
  const T = window.I18N[lang];
  return (
    <section className="section" id="now">
      <div className="shell">
        <SectionHead idx="07" cmd={T.now_cmd} title={T.now_title} count={T.now_focus} />
        <div className="now">
          <div className="now-card">
            <div className="now-head"><span className="icon"></span> {T.now_ship}</div>
            <div className="now-title">{T.now_card1_title}</div>
            <div className="now-desc">{T.now_card1_desc}</div>
          </div>
          <div className="now-card">
            <div className="now-head"><span className="icon"></span> {T.now_research}</div>
            <div className="now-title">{T.now_card2_title}</div>
            <div className="now-desc">{T.now_card2_desc}</div>
          </div>
          <div className="now-card">
            <div className="now-head"><span className="icon"></span> {T.now_read}</div>
            <div className="now-title">{T.now_card3_title}</div>
            <div className="now-desc">{T.now_card3_desc}</div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------- Contact ---------- */

function Contact({ lang }) {
  const T = window.I18N[lang];
  return (
    <section className="contact" id="contact">
      <div className="shell">
        <SectionHead idx="08" cmd={T.contact_cmd} title={T.contact_title} count="CTA" />
        <h2 className="contact-line">
          {T.contact_line1} <span className="accent">{T.contact_line1_hl}</span>?
          <br />
          <span className="dim">{T.contact_line2_dim}</span>{T.contact_line2}
        </h2>

        <a className="contact-cta" href="mailto:hello@hireadev.tech">
          <span>{T.contact_cta}</span>
          <span className="arr">↗</span>
        </a>

        <div className="contact-grid">
          <div className="cg">
            <div className="cg-l">{T.cg_email}</div>
            <a className="cg-v" href="mailto:hello@hireadev.tech">hello@hireadev.tech</a>
          </div>
          <div className="cg">
            <div className="cg-l">{T.cg_github}</div>
            <a className="cg-v" href="https://github.com/mayur-champaneria" target="_blank" rel="noopener">@mayur-champaneria ↗</a>
          </div>
          <div className="cg">
            <div className="cg-l">{T.cg_linkedin}</div>
            <a className="cg-v" href="https://www.linkedin.com/in/mayur-champaneria" target="_blank" rel="noopener">/in/mayur-champaneria ↗</a>
          </div>
          <div className="cg">
            <div className="cg-l">{T.cg_resume}</div>
            <a className="cg-v" href="cv.pdf" id="dl-cv">{T.cg_resume_val}</a>
          </div>
        </div>

        <div className="foot">
          <span>{T.footer_left}</span>
          <span>{T.footer_right}</span>
        </div>
      </div>
    </section>
  );
}

/* ---------- Command Palette ---------- */

function CommandPalette({ open, onClose, lang, onToggleLang }) {
  const T = window.I18N[lang];
  const [q, setQ] = useStateB("");
  const [idx, setIdx] = useStateB(0);
  const inputRef = useRefB(null);

  const items = useMemoB(() => [
    { id: "to-work",    label: T.cmd_goto_work,    sub: "section · 01",                     ic: "→", action: () => scrollTo("#work") },
    { id: "to-case",    label: T.cmd_goto_case,    sub: "section · 02",                     ic: "★", action: () => scrollTo("#case") },
    { id: "to-skills",  label: T.cmd_goto_skills,  sub: "section · 03",                     ic: "→", action: () => scrollTo("#skills") },
    { id: "to-exp",     label: T.cmd_goto_exp,     sub: "section · 04",                     ic: "→", action: () => scrollTo("#experience") },
    { id: "to-gh",      label: T.cmd_goto_gh,      sub: "section · 05",                     ic: "→", action: () => scrollTo("#github") },
    { id: "to-writing", label: T.cmd_goto_writing, sub: "section · 06",                     ic: "→", action: () => scrollTo("#writing") },
    { id: "to-now",     label: T.cmd_goto_now,     sub: "section · 07",                     ic: "→", action: () => scrollTo("#now") },
    { id: "to-contact", label: T.cmd_goto_contact, sub: "section · 08",                     ic: "→", action: () => scrollTo("#contact") },
    { id: "github",     label: T.cmd_open_gh,      sub: "github.com/mayur-champaneria",      ic: "↗", action: () => window.open("https://github.com/mayur-champaneria", "_blank") },
    { id: "linkedin",   label: T.cmd_open_li,      sub: "linkedin.com/in/mayur-champaneria", ic: "↗", action: () => window.open("https://www.linkedin.com/in/mayur-champaneria", "_blank") },
    { id: "email",      label: T.cmd_email,        sub: "hello@hireadev.tech",               ic: "✎", action: () => { window.location.href = "mailto:hello@hireadev.tech"; } },
    { id: "cv",         label: T.cmd_cv,           sub: T.cmd_cv_sub,                        ic: "↓", action: () => { window.location.href = "cv.pdf"; } },
    { id: "theme",      label: T.cmd_theme,        sub: T.cmd_theme_sub,                     ic: "◐", action: () => window.__toggleTheme && window.__toggleTheme() },
    { id: "lang",       label: T.cmd_lang,         sub: T.cmd_lang_sub,                      ic: "⌨", action: () => { onToggleLang(); } },
    { id: "egg",        label: T.cmd_egg,          sub: T.cmd_egg_sub,                       ic: "✦", action: () => window.__easterEgg && window.__easterEgg() },
  ], [lang]);

  const filtered = items.filter((i) => i.label.toLowerCase().includes(q.toLowerCase()) || i.sub.toLowerCase().includes(q.toLowerCase()));

  useEffectB(() => {
    if (open) setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
    else { setQ(""); setIdx(0); }
  }, [open]);

  useEffectB(() => { setIdx(0); }, [q]);

  const onKey = (e) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setIdx((i) => Math.min(filtered.length - 1, i + 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setIdx((i) => Math.max(0, i - 1)); }
    else if (e.key === "Enter") {
      e.preventDefault();
      const it = filtered[idx];
      if (it) { it.action(); onClose(); }
    }
    else if (e.key === "Escape") onClose();
  };

  function scrollTo(sel) {
    const el = document.querySelector(sel);
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 60;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
  }

  if (!open) return null;
  return (
    <div className="cmdk-overlay" onClick={onClose}>
      <div className="cmdk" onClick={(e) => e.stopPropagation()}>
        <div className="cmdk-input">
          <span className="pr">$</span>
          <input
            ref={inputRef}
            placeholder={T.cmd_placeholder}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={onKey}
          />
          <span className="kbd">ESC</span>
        </div>
        <div className="cmdk-list">
          {filtered.length === 0 && <div style={{ padding: "12px 16px", color: "var(--fg-dim)", fontSize: 13 }}>{T.cmd_no_match}</div>}
          {filtered.map((it, i) => (
            <div key={it.id} className={"cmdk-item" + (i === idx ? " active" : "")} onMouseEnter={() => setIdx(i)} onClick={() => { it.action(); onClose(); }}>
              <span className="ic">{it.ic}</span>
              <span><span className="lbl">{it.label}</span></span>
              <span className="sub">{it.sub}</span>
            </div>
          ))}
        </div>
        <div className="cmdk-foot">
          <span>{T.cmd_nav}</span>
          <span>{T.cmd_select}</span>
          <span>{T.cmd_close}</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Skills, Experience, GithubGraph, Writing, Now, Contact, CommandPalette });
