// ============================================================
// Alprovid — Portfolio, Process, Testimonials, Contact, Footer, WA
// ============================================================

const FILTERS = [
{ id: "all", label: "הכל", layout: "mixed" },
{ id: "social", label: "סושיאל", layout: "vertical" },
{ id: "courses", label: "קורסים", layout: "horizontal" },
{ id: "podcasts", label: "פודקאסטים", layout: "horizontal" },
{ id: "family", label: "משפחה", layout: "vertical" },
{ id: "army", label: "צבא", layout: "vertical" }];


// Fallback list — used ONLY if content/portfolio.json fails to load.
// The real source of truth is content/portfolio.json (editable via the CMS).
const PF_ITEMS_FALLBACK = [
{ id: 1, cat: "social", title: "ריל תדמית", client: "PLAYCAST", orient: "v", autoplay: true, mark: "✦", tint: 0 },
{ id: 2, cat: "social", title: "סרטון קמפיין", client: "DIFFERENT", orient: "v", autoplay: true, mark: "◇", tint: 2 },
{ id: 3, cat: "social", title: "ריל מוצר", client: "RE/MAX", orient: "v", autoplay: true, mark: "▲", tint: 3 },
{ id: 4, cat: "social", title: "תוכן יומי", client: "יש מצ׳ין", orient: "v", autoplay: true, mark: "✺", tint: 4 },
{ id: 5, cat: "courses", title: "פתיחה לקורס", client: "פסח פרקוף", orient: "h", autoplay: false, mark: "◐", tint: 1 },
{ id: 6, cat: "courses", title: "שיעור מודולרי", client: "גיטרה ב-5", orient: "h", autoplay: false, mark: "◑", tint: 5 },
{ id: 7, cat: "podcasts", title: "פרק אורח", client: "PLAYCAST", orient: "h", autoplay: false, mark: "✺", tint: 0 },
{ id: 8, cat: "podcasts", title: "ריאיון עומק", client: "PODCAST", orient: "h", autoplay: false, mark: "◉", tint: 2 },
{ id: 9, cat: "family", title: "תיעוד אירוע", client: "אישי", orient: "v", autoplay: true, mark: "♥", tint: 4 },
{ id: 10, cat: "family", title: "סיכום שנה", client: "אישי", orient: "v", autoplay: true, mark: "✦", tint: 1 },
{ id: 11, cat: "army", title: "סיכום מסלול", client: "סיירת", orient: "v", autoplay: true, mark: "▲", tint: 3 },
{ id: 12, cat: "army", title: "חלוקת כומתה", client: "צה״ל", orient: "v", autoplay: true, mark: "◇", tint: 5 }];


// Normalize a content JSON item to the internal card shape.
function normItem(it) {
  return {
    id: it.id,
    cat: it.category || it.cat,
    title: it.title,
    client: it.client,
    orient: (it.orientation === "horizontal" || it.orient === "h") ? "h" : "v",
    video: it.video || "",
    poster: it.poster || "",
    autoplay: !!it.autoplay,
    mark: it.mark,
    tint: it.tint || 0 };

}

const MOBILE_LIMIT = 6;

function Portfolio() {
  const [active, setActive] = useState("all");
  const [fading, setFading] = useState(false);
  const [lightbox, setLightbox] = useState(null);
  const [showAll, setShowAll] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [items, setItems] = useState(PF_ITEMS_FALLBACK);

  useEffect(() => {
    const mq = window.matchMedia("(max-width: 560px)");
    const update = () => setIsMobile(mq.matches);
    update();
    mq.addEventListener("change", update);
    return () => mq.removeEventListener("change", update);
  }, []);

  // Load portfolio content (videos/posters) from the CMS-editable JSON.
  useEffect(() => {
    fetch("content/portfolio.json", { cache: "no-cache" }).
    then((r) => r.ok ? r.json() : null).
    then((d) => {if (d && Array.isArray(d.items)) setItems(d.items.map(normItem));}).
    catch(() => {});
  }, []);

  const layout = FILTERS.find((f) => f.id === active).layout;
  const visible = useMemo(() => active === "all" ? items : items.filter((i) => i.cat === active), [active, items]);

  const limited = isMobile && !showAll ? visible.slice(0, MOBILE_LIMIT) : visible;
  const canExpand = isMobile && visible.length > MOBILE_LIMIT;

  const onFilter = (id) => {
    if (id === active) return;
    setFading(true);
    setShowAll(false);
    setTimeout(() => {setActive(id);setFading(false);}, 260);
  };

  const spanStyle = (it, i) => {
    if (layout !== "mixed" || isMobile) {
      if (layout === "mixed" && isMobile && it.orient === "h") return { gridColumn: "1 / -1" };
      return undefined;
    }
    if (it.orient === "h") return { gridColumn: "span 3", gridRow: "span 4" };
    return { gridColumn: "span 2", gridRow: i % 4 === 0 ? "span 6" : "span 5" };
  };

  const cardClass = (it) => {
    let c = "pf-card";
    if (layout === "vertical") c += " v";else
    if (layout === "horizontal") c += " h";else
    if (isMobile) c += it.orient === "h" ? " h" : " v"; // mobile mixed
    return c;
  };

  const close = useCallback(() => setLightbox(null), []);
  const nav = useCallback((dir) => setLightbox((cur) => cur === null ? cur : (cur + dir + visible.length) % visible.length), [visible.length]);

  useEffect(() => {
    if (lightbox === null) return;
    const onKey = (e) => {
      if (e.key === "Escape") close();else
      if (e.key === "ArrowRight") nav(-1);else
      if (e.key === "ArrowLeft") nav(1);
    };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKey);
    return () => {document.body.style.overflow = "";window.removeEventListener("keydown", onKey);};
  }, [lightbox, close, nav]);

  const lb = lightbox !== null ? visible[lightbox] : null;

  return (
    <section className="section portfolio" id="portfolio">
      <Reveal as="h2">
        <Typewriter lines={["תיק עבודות", "לסרטונים יש מה להגיד :)", "קצת ממה שעשיתי לאחרונה"]} typeSpeed={50} deleteSpeed={28} holdMs={2800} />
      </Reveal>

      <Reveal as="div" className="filters" delay={120}>
        {FILTERS.map((f) =>
        <button key={f.id} className={`filter-pill ${active === f.id ? "active" : ""}`} onClick={() => onFilter(f.id)}>{f.label}</button>
        )}
      </Reveal>

      <div className={`portfolio-grid ${layout} ${fading ? "fading" : ""}`}>
        {limited.map((it, i) =>
        <div key={it.id} className={cardClass(it)} style={spanStyle(it, i)} onClick={() => setLightbox(visible.indexOf(it))}>
            <div className="pf-media"><Media src={it.src} video={it.video} poster={it.poster} autoplay={it.autoplay} mark={it.mark} tint={it.tint} alt={it.title} /></div>
            <div className="pf-hover-bg" />
            {!(it.video && it.autoplay) && <div className="play" />}
            <div className="pf-hover">
              <div className="t">{it.title}</div>
              <div className="c ltr">{it.client}</div>
            </div>
          </div>
        )}
      </div>

      {canExpand &&
      <div className="pf-more">
          <button onClick={() => setShowAll((s) => !s)}>
            {showAll ? "הצג פחות" : `עוד עבודות (${visible.length - MOBILE_LIMIT}) ←`}
          </button>
        </div>
      }

      {lb &&
      <div className="lightbox" onClick={close}>
          <div className="lightbox-inner" onClick={(e) => e.stopPropagation()}>
            <button className="lightbox-close" onClick={close} aria-label="סגירה">✕</button>
            <button className="lightbox-arrow prev" onClick={() => nav(-1)} aria-label="הקודם">→</button>
            <button className="lightbox-arrow next" onClick={() => nav(1)} aria-label="הבא">←</button>
            <div className={`lightbox-media ${lb.orient}`}>
              {lb.video ?
              <video src={mediaUrl(lb.video)} poster={mediaUrl(lb.poster) || undefined} controls autoPlay playsInline style={{ width: "100%", height: "100%", objectFit: "contain", background: "#000" }} /> :

              <Media src={lb.src} mark={lb.mark} tint={lb.tint} alt={lb.title} loading="eager" />}
            </div>
            <div className="lightbox-meta">
              <div className="t">{lb.title}</div>
              <div className="c ltr">{`${lightbox + 1} / ${visible.length}`}</div>
            </div>
          </div>
        </div>
      }
    </section>);

}

/* ---------- PROCESS ---------- */
function Process() {
  const steps = [
  { n: "01", k: "תיאום", body: <>מתאמים ציפיות.</> },
  { n: "02", k: "עריכה", body: <>אני נכנס לעריכה.</> },
  { n: "03", k: "מסירה", body: <>אתה מקבל את התוצר לפני הזמן <span className="em">—</span> כי <span className="punch">״בזמן״</span> זה באיחור.</> }];

  return (
    <section className="section process">
      <Reveal as="h2">איך זה עובד?</Reveal>
      <div className="proc-grid">
        {steps.map((s, i) =>
        <Reveal as="div" key={i} className="proc-cell" delay={i * 130}>
            <div className="proc-rule"><span /></div>
            <div className="proc-head">
              <span className="proc-n ltr">{s.n}</span>
              <span className="proc-k">{s.k}</span>
            </div>
            <div className="proc-body">{s.body}</div>
          </Reveal>
        )}
      </div>
      <Reveal as="div" className="proc-arrow" delay={420}>
        <svg viewBox="0 0 260 150" fill="none" aria-hidden="true">
          <path className="pa-line" d="M26 16 C 2 62, 88 82, 122 74 C 160 66, 178 82, 166 120" stroke="var(--accent)" strokeWidth="3" strokeLinecap="round" />
          <path className="pa-head" d="M166 122 L 184 102 M166 122 L 146 112" stroke="var(--accent)" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </Reveal>
      <Reveal as="div" className="process-signoff" delay={560}>הלקוחות שלי מופתעים מזה <span className="smile">:)</span></Reveal>
    </section>);

}

/* ---------- TESTIMONIALS (real Midrag reviews) ---------- */
const REVIEWS = [
{ quote: "מבחינה מקצועית עשה עבודה ממש מעולה ונתן שירות טוב! ומבחינה אישית כיף לעבוד איתו. המלצתי עליו לחבר שלקח את שירותיו, ואעבוד איתו גם בעתיד.", name: "מיקי סוויסה", role: "יבנה · צילום סרטוני תדמית", initials: "מ.ס" },
{ quote: "היה מצוין! ממש מקצועי ושירותי, היה לי תענוג לעבוד איתו. מומלץ ביותר!", name: "הילה מזור", role: "ירושלים · עריכה לסושיאל", initials: "ה.מ" },
{ quote: "היה מצוין! עבד במהירות, עשה סרטונים איכותיים והחוויה הייתה טובה!", name: "דקלה דון", role: "כמהין · הפקת סרטונים לעסק", initials: "ד.ד" },
{ quote: "הוא היה מצוין, אין עליו! תותח על — ועשה עבודה מעולה!", name: "אליהו מזוז", role: "יבנה · עריכת סרטונים", initials: "א.מ" },
{ quote: "אני ממליצה מאוד! הוא מקצועי, נעים ועשה עבודה טובה.", name: "מיכל שר שלום", role: "כמהין · סרטוני עדויות", initials: "מ.ש" },
{ quote: "ממש אלוף, אחלה של בחור. עבודה נקייה ומדויקת.", name: "ליאור כהן", role: "ירושלים · עריכת וידאו", initials: "ל.כ" }];


function Testimonials() {
  return (
    <section className="section testimonials">
      <Reveal as="h2">
        <Typewriter lines={["מה אומרים עליי", "לקוחות מרוצים :)", "אל תאמינו לי. תאמינו להם."]} typeSpeed={50} deleteSpeed={28} holdMs={2800} />
      </Reveal>
      <div className="testimonial-grid">
        {REVIEWS.map((r, i) =>
        <Reveal as="div" key={i} className="t-card" delay={i % 3 * 90}>
            <div className="t-stars" aria-label="חמישה כוכבים">★★★★★</div>
            <p className="t-quote">{r.quote}</p>
            <div className="t-divider" />
            <div className="t-meta">
              <div className="t-avatar">{r.initials}</div>
              <div>
                <div className="t-name">{r.name}</div>
                <div className="t-role">{r.role}</div>
              </div>
            </div>
          </Reveal>
        )}
      </div>
      <div className="swipe-hint" aria-hidden="true">החליקו לעוד המלצות ←</div>
    </section>);

}

/* ---------- CONTACT ---------- */
const WAIcon = () =>
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M17.5 14.4c-.3-.2-1.8-.9-2.1-1-.3-.1-.5-.1-.7.1-.2.3-.8 1-1 1.2-.2.2-.4.2-.7.1-1-.5-1.8-1-2.6-1.8-.7-.8-1.2-1.6-1.4-2.2-.2-.5.1-.7.2-.8.2-.1.4-.4.6-.6.2-.2.2-.4.3-.6.1-.2.1-.4 0-.6-.1-.2-.7-1.7-.9-2.3-.2-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 .9-1 2.3 0 1.4 1 2.7 1.1 2.9.1.2 2 3 4.8 4.2.7.3 1.2.5 1.6.6.7.2 1.3.2 1.8.1.5-.1 1.8-.7 2.1-1.5.3-.7.3-1.4.2-1.5-.1-.1-.3-.2-.6-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.2-1.3c1.4.8 3 1.3 4.8 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18.2c-1.6 0-3.1-.4-4.4-1.2l-.3-.2-3.2.8.8-3.1-.2-.3c-.9-1.4-1.3-3-1.3-4.6 0-4.5 3.7-8.2 8.2-8.2s8.2 3.7 8.2 8.2-3.7 8.2-8.2 8.2z" /></svg>;

const MailIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M3 7l9 6 9-6" /></svg>;

const PhoneIcon = () =>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6A19.79 19.79 0 0 1 2.12 4.18 2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z" /></svg>;


function Contact() {
  return (
    <section className="section contact" id="contact">
      <Reveal as="h2">
        <span className="soft">זה רק סוף הדף.</span>
        שנתחיל? <span className="smile">:)</span>
      </Reveal>
      <Reveal as="div" className="contact-buttons" delay={120}>
        <a className="contact-btn" href="https://wa.me/972545994616" target="_blank" rel="noopener noreferrer">
          <div className="ico"><WAIcon /></div>
          <div className="label-row"><span className="label">WhatsApp</span><span className="value ltr">054-5994616</span></div>
        </a>
        <a className="contact-btn" href="mailto:AL.Pro.Vid@gmail.com">
          <div className="ico"><MailIcon /></div>
          <div className="label-row"><span className="label">מייל</span><span className="value ltr">AL.Pro.Vid@gmail.com</span></div>
        </a>
        <a className="contact-btn" href="tel:+972545994616">
          <div className="ico"><PhoneIcon /></div>
          <div className="label-row"><span className="label">טלפון</span><span className="value ltr">054-5994616</span></div>
        </a>
      </Reveal>
    </section>);

}

/* ---------- FOOTER ---------- */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-brand">אברהם לוי <span className="sep">·</span> עורך וידאו <span className="sep">·</span> ירושלמי</div>
      <div className="footer-copy ltr">© 2026 Alprovid | כל הזכויות שמורות</div>
    </footer>);

}

/* ---------- FLOATING WHATSAPP ---------- */
function WAFloat() {
  return (
    <a className="wa-float" href="https://wa.me/972545994616" target="_blank" rel="noopener noreferrer" aria-label="פתח שיחה בוואטסאפ">
      <WAIcon />
    </a>);

}

Object.assign(window, { Portfolio, Process, Testimonials, Contact, Footer, WAFloat });