/* ============================================================
   App showcase building blocks.
     <AppIcon />       — squircle gradient icon w/ initials
     <StoreBadge />    — App Store / Play Store / Web pills
     <StatusBadge />   — Live / Beta / In Build chip
     <PlatformChips /> — icon row for ios/android/web
     <Rating />        — stars + count
     <AppScreen />     — fake mobile screenshot keyed on `kind`
     <AppFrame />      — iOS device frame wrapping AppScreen
   ============================================================ */

/* The home page's app cards let the user drop a custom icon per app; those
   live in the shared sidecar `image-slots-index.state.json` under the id
   `app-<slug>-icon`. Reuse the exact same icons here. Fetched once, cached. */
let __appIconStoreP = null;
function loadAppIconStore() {
  if (!__appIconStoreP) {
    __appIconStoreP = fetch("image-slots-index.state.json")
      .then((r) => (r.ok ? r.json() : {}))
      .catch(() => ({}));
  }
  return __appIconStoreP;
}

function AppIcon({ app, size = 56, hover = false }) {
  const { hue = 250, hue2 = 200, initials = "" } = app.icon || {};
  const c1 = `oklch(0.68 0.18 ${hue})`;
  const c2 = `oklch(0.45 0.20 ${hue2})`;
  const [img, setImg] = React.useState(null);
  React.useEffect(() => {
    let on = true;
    loadAppIconStore().then((store) => {
      if (!on) return;
      const v = store && store[`app-${app.slug}-icon`];
      const u = v && (typeof v === "string" ? v : v.u);
      if (u && /^data:image\//.test(u)) setImg(u);
    });
    return () => { on = false; };
  }, [app.slug]);
  return (
    <span
      className={`app-icon ${hover ? "app-icon--hover" : ""}`}
      style={{
        width: size,
        height: size,
        borderRadius: Math.round(size * 0.234),
        background: img ? "#0a0a0c" : `linear-gradient(135deg, ${c1}, ${c2})`,
        fontSize: Math.round(size * 0.36),
        overflow: "hidden",
      }}
      aria-hidden="true"
    >
      {img ? (
        <img src={img} alt="" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
      ) : (
        <>
          <span className="app-icon__shine" aria-hidden="true"></span>
          <span className="app-icon__inner">{initials}</span>
        </>
      )}
    </span>
  );
}

function StatusBadge({ status }) {
  const map = {
    live:    { label: "Live",     cls: "status-badge--live" },
    beta:    { label: "Beta",     cls: "status-badge--beta" },
    build:   { label: "In Build", cls: "status-badge--build" },
  };
  const s = map[status] || map.live;
  return (
    <span className={`status-badge ${s.cls}`}>
      <span className="status-badge__dot" aria-hidden="true"></span>
      {s.label}
    </span>
  );
}

function PlatformChips({ platforms, size = "sm" }) {
  const ICONS = {
    ios: (
      <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
        <path d="M17.05 12.04c-.03-3.07 2.5-4.55 2.62-4.62-1.43-2.09-3.65-2.38-4.44-2.4-1.89-.19-3.69 1.11-4.65 1.11-.98 0-2.45-1.09-4.03-1.06-2.07.03-3.99 1.2-5.06 3.05-2.16 3.74-.55 9.27 1.55 12.31 1.03 1.49 2.25 3.17 3.85 3.11 1.55-.06 2.13-1 4.01-1 1.86 0 2.4 1 4.04.97 1.67-.03 2.73-1.51 3.75-3.01 1.18-1.73 1.66-3.4 1.69-3.49-.04-.02-3.24-1.24-3.33-4.97zm-3.07-9.13c.86-1.04 1.43-2.48 1.27-3.91-1.24.05-2.74.83-3.62 1.85-.8.92-1.49 2.4-1.3 3.81 1.38.11 2.79-.7 3.65-1.75z"/>
      </svg>
    ),
    android: (
      <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
        <path d="M5.84 11.95v5.66c0 .8.65 1.45 1.45 1.45h.5v3.13a1.45 1.45 0 1 0 2.9 0v-3.13h2.62v3.13a1.45 1.45 0 1 0 2.9 0v-3.13h.5c.8 0 1.45-.65 1.45-1.45v-5.66h-12.32zm-1.65-.07a1.45 1.45 0 1 0 0 2.9c.8 0 1.45-.65 1.45-1.45v-1.45zm15.62 0a1.45 1.45 0 0 0-1.45 1.45v1.45a1.45 1.45 0 1 0 2.9 0 1.45 1.45 0 0 0-1.45-1.45zM15.5 4.5l1.04-1.86a.36.36 0 0 0-.14-.5.36.36 0 0 0-.5.14L14.84 4.13a8.31 8.31 0 0 0-5.68 0L8.1 2.28a.36.36 0 0 0-.5-.14.36.36 0 0 0-.14.5L8.5 4.5C6.66 5.55 5.46 7.29 5.34 9.4h13.32C18.54 7.29 17.34 5.55 15.5 4.5zM9.5 7.5a.6.6 0 1 1 0-1.2.6.6 0 0 1 0 1.2zm5 0a.6.6 0 1 1 0-1.2.6.6 0 0 1 0 1.2z"/>
      </svg>
    ),
    web: (
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" aria-hidden="true">
        <circle cx="12" cy="12" r="9"/>
        <path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/>
      </svg>
    ),
  };
  return (
    <span className={`platforms platforms--${size}`}>
      {platforms.map((p) => (
        <span key={p} className="platforms__chip" aria-label={p}>
          {ICONS[p]}
        </span>
      ))}
    </span>
  );
}

function Rating({ value, reviews }) {
  // Render 5 stars filled by `value` (0–5).
  const full = Math.floor(value);
  const frac = value - full;
  return (
    <span className="rating" aria-label={`${value} out of 5 stars`}>
      <span className="rating__stars" aria-hidden="true">
        {[0,1,2,3,4].map((i) => {
          const fill = i < full ? 1 : (i === full ? frac : 0);
          return (
            <span key={i} className="rating__star">
              <svg viewBox="0 0 16 16" width="13" height="13">
                <defs>
                  <linearGradient id={`star-${i}-${Math.round(value*10)}`}>
                    <stop offset={`${fill * 100}%`}  stopColor="oklch(0.78 0.16 75)"/>
                    <stop offset={`${fill * 100}%`}  stopColor="currentColor"/>
                  </linearGradient>
                </defs>
                <path d="M8 1.5l1.9 4.05 4.45.45-3.35 3.05.95 4.4L8 11.2 4.05 13.45 5 9.05 1.65 6l4.45-.45z"
                      fill={`url(#star-${i}-${Math.round(value*10)})`}/>
              </svg>
            </span>
          );
        })}
      </span>
      <span className="rating__val">{value.toFixed(1)}</span>
      {reviews != null ? <span className="rating__count">({reviews.toLocaleString()})</span> : null}
    </span>
  );
}

function StoreBadge({ kind, href }) {
  const props = {
    href: href || "#",
    target: "_blank",
    rel: "noreferrer noopener",
    className: `store-badge store-badge--${kind}`,
    "data-cursor": "Get it",
  };
  if (kind === "ios") {
    return (
      <a {...props}>
        <span className="store-badge__icon">
          <svg viewBox="0 0 24 24" fill="currentColor" width="22" height="22">
            <path d="M17.05 12.04c-.03-3.07 2.5-4.55 2.62-4.62-1.43-2.09-3.65-2.38-4.44-2.4-1.89-.19-3.69 1.11-4.65 1.11-.98 0-2.45-1.09-4.03-1.06-2.07.03-3.99 1.2-5.06 3.05-2.16 3.74-.55 9.27 1.55 12.31 1.03 1.49 2.25 3.17 3.85 3.11 1.55-.06 2.13-1 4.01-1 1.86 0 2.4 1 4.04.97 1.67-.03 2.73-1.51 3.75-3.01 1.18-1.73 1.66-3.4 1.69-3.49-.04-.02-3.24-1.24-3.33-4.97zm-3.07-9.13c.86-1.04 1.43-2.48 1.27-3.91-1.24.05-2.74.83-3.62 1.85-.8.92-1.49 2.4-1.3 3.81 1.38.11 2.79-.7 3.65-1.75z"/>
          </svg>
        </span>
        <span className="store-badge__text">
          <span className="store-badge__sup">Download on the</span>
          <span className="store-badge__main">App Store</span>
        </span>
      </a>
    );
  }
  if (kind === "android") {
    return (
      <a {...props}>
        <span className="store-badge__icon">
          <svg viewBox="0 0 24 24" width="22" height="22">
            <linearGradient id="ps-1" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0" stopColor="#00b9ff"/>
              <stop offset="1" stopColor="#0067ff"/>
            </linearGradient>
            <linearGradient id="ps-2" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0" stopColor="#ffd200"/>
              <stop offset="1" stopColor="#ff9500"/>
            </linearGradient>
            <linearGradient id="ps-3" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor="#ff424b"/>
              <stop offset="1" stopColor="#c80031"/>
            </linearGradient>
            <linearGradient id="ps-4" x1="0" y1="1" x2="1" y2="0">
              <stop offset="0" stopColor="#00d77f"/>
              <stop offset="1" stopColor="#00b452"/>
            </linearGradient>
            <path d="M3.5 2.2c-.32.27-.5.7-.5 1.25v17.1c0 .54.18.97.5 1.25l9.1-9.4-9.1-10.2z" fill="url(#ps-1)"/>
            <path d="M16.6 8.4l-3.6 3.6 3.6 3.6 4.3-2.4c1.2-.7 1.2-2.4 0-3.1l-4.3-1.7z" fill="url(#ps-2)"/>
            <path d="M3.5 21.8c.38.32.99.36 1.66-.02l11.44-6.4-3.6-3.4-9.5 9.82z" fill="url(#ps-3)"/>
            <path d="M3.5 2.2l9.5 9.8 3.6-3.6L5.16 2.22c-.67-.38-1.28-.34-1.66 0z" fill="url(#ps-4)"/>
          </svg>
        </span>
        <span className="store-badge__text">
          <span className="store-badge__sup">Get it on</span>
          <span className="store-badge__main">Google Play</span>
        </span>
      </a>
    );
  }
  return (
    <a {...props}>
      <span className="store-badge__icon">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" width="22" height="22">
          <circle cx="12" cy="12" r="9"/>
          <path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/>
        </svg>
      </span>
      <span className="store-badge__text">
        <span className="store-badge__sup">Open the</span>
        <span className="store-badge__main">Web app</span>
      </span>
    </a>
  );
}

/* ----- Faux app screens ----- */

function AppScreen({ kind, app }) {
  const hue = app?.cover?.hue ?? 250;
  const hue2 = app?.cover?.hue2 ?? 200;
  const bg = `linear-gradient(180deg, oklch(0.99 0.005 ${hue}), oklch(0.96 0.01 ${hue}))`;
  const accent = `oklch(0.55 0.18 ${hue})`;
  return (
    <div className="appscreen" style={{ background: bg, "--app-accent": accent }}>
      <div className="appscreen__header">
        <div className="appscreen__avatar" style={{ background: `linear-gradient(135deg, oklch(0.68 0.18 ${hue}), oklch(0.45 0.2 ${hue2}))` }}>{app?.icon?.initials || ""}</div>
        <div className="appscreen__title">
          <div className="appscreen__name">{app?.name || "Studio"}</div>
          <div className="appscreen__sub">{kind === "dashboard" ? "Overview" : kind === "fx" ? "FX desk" : kind === "list" ? "Activity" : kind === "consult" ? "Live consult" : kind === "schedule" ? "Calendar" : kind === "map" ? "Routes" : kind === "lesson" ? "Lesson" : kind === "chat" ? "Tutor" : ""}</div>
        </div>
        <div className="appscreen__chip" aria-hidden="true"></div>
      </div>

      {kind === "dashboard" && <ScreenDashboard accent={accent} />}
      {kind === "fx"        && <ScreenFX        accent={accent} />}
      {kind === "list"      && <ScreenList      accent={accent} />}
      {kind === "consult"   && <ScreenConsult   accent={accent} app={app} />}
      {kind === "schedule"  && <ScreenSchedule  accent={accent} />}
      {kind === "map"       && <ScreenMap       accent={accent} />}
      {kind === "lesson"    && <ScreenLesson    accent={accent} />}
      {kind === "chat"      && <ScreenChat      accent={accent} app={app} />}

      <div className="appscreen__tabbar">
        <span className="appscreen__tab is-active"></span>
        <span className="appscreen__tab"></span>
        <span className="appscreen__tab"></span>
        <span className="appscreen__tab"></span>
      </div>
    </div>
  );
}

function ScreenDashboard({ accent }) {
  return (
    <div className="appscreen__body">
      <div className="appscreen__hero">
        <div className="appscreen__hero-label">Total balance</div>
        <div className="appscreen__hero-val">$ 4,820,940</div>
        <div className="appscreen__hero-meta" style={{ color: accent }}>▲ 2.4%   vs last week</div>
      </div>
      <div className="appscreen__cards">
        {[1,2,3].map(i => (
          <div key={i} className="appscreen__card">
            <div className="appscreen__card-h"></div>
            <div className="appscreen__card-v"></div>
            <div className="appscreen__card-bar"></div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ScreenFX({ accent }) {
  return (
    <div className="appscreen__body">
      <div className="appscreen__pair">
        <span>USD → AED</span>
        <strong>3.6731</strong>
      </div>
      <svg className="appscreen__chart" viewBox="0 0 280 110" preserveAspectRatio="none" aria-hidden="true">
        <defs>
          <linearGradient id="fx-fill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor={accent} stopOpacity="0.25"/>
            <stop offset="1" stopColor={accent} stopOpacity="0"/>
          </linearGradient>
        </defs>
        <path d="M0,80 C40,60 70,90 110,55 C150,20 190,70 230,40 C260,18 280,30 280,30 L280,110 L0,110 Z" fill="url(#fx-fill)"/>
        <path d="M0,80 C40,60 70,90 110,55 C150,20 190,70 230,40 C260,18 280,30 280,30" stroke={accent} strokeWidth="1.8" fill="none" strokeLinecap="round"/>
      </svg>
      <div className="appscreen__pillrow">
        <span className="appscreen__pill" style={{ color: accent, borderColor: accent }}>Buy</span>
        <span className="appscreen__pill">Sell</span>
        <span className="appscreen__pill">Hedge</span>
      </div>
    </div>
  );
}

function ScreenList({ accent }) {
  return (
    <div className="appscreen__body">
      {[
        ["Standard Chartered",  "+ $42,000"],
        ["ENBD Treasury",        "− $12,400"],
        ["Aramex AR",            "+ $3,820"],
        ["Mashreq Payroll",      "− $58,200"],
        ["Stripe payouts",       "+ $1,940"],
      ].map(([n, v], i) => (
        <div key={i} className="appscreen__row">
          <span className="appscreen__row-dot" style={{ background: accent }}></span>
          <span className="appscreen__row-name">{n}</span>
          <span className={`appscreen__row-val ${v.startsWith("+") ? "is-up" : "is-down"}`}>{v}</span>
        </div>
      ))}
    </div>
  );
}

function ScreenConsult({ accent, app }) {
  return (
    <div className="appscreen__body">
      <div className="appscreen__video" style={{ background: `linear-gradient(160deg, oklch(0.62 0.16 ${app?.cover?.hue || 250}), oklch(0.32 0.14 ${app?.cover?.hue2 || 200}))` }}>
        <span className="appscreen__video-tag">LIVE · 04:21</span>
        <span className="appscreen__avatar appscreen__avatar--big" style={{ background: "rgba(255,255,255,0.18)", color: "#fff" }}>FN</span>
      </div>
      <div className="appscreen__caption">Dr. Farah N. · GP</div>
      <div className="appscreen__pillrow">
        <span className="appscreen__pill" style={{ color: accent, borderColor: accent }}>Notes</span>
        <span className="appscreen__pill">Rx</span>
        <span className="appscreen__pill">End</span>
      </div>
    </div>
  );
}

function ScreenSchedule({ accent }) {
  const days = ["M","T","W","T","F","S","S"];
  return (
    <div className="appscreen__body">
      <div className="appscreen__weekrow">
        {days.map((d,i) => (
          <span key={i} className={`appscreen__day ${i===2 ? "is-active" : ""}`} style={i===2 ? { background: accent, color: "#fff" } : null}>
            <small>{d}</small>
            <strong>{i + 12}</strong>
          </span>
        ))}
      </div>
      {[
        ["09:30", "Move-in · Marina 3-bd"],
        ["13:00", "Cleaning · Bluewaters"],
        ["16:45", "Owner call · Palm"],
      ].map(([t, l], i) => (
        <div key={i} className="appscreen__schedule-row">
          <span className="appscreen__schedule-t">{t}</span>
          <span className="appscreen__schedule-l">
            <span className="appscreen__row-dot" style={{ background: accent }}></span>
            {l}
          </span>
        </div>
      ))}
    </div>
  );
}

function ScreenMap({ accent }) {
  return (
    <div className="appscreen__body">
      <div className="appscreen__map" aria-hidden="true">
        <svg viewBox="0 0 280 180" preserveAspectRatio="none">
          <defs>
            <pattern id="grid" width="14" height="14" patternUnits="userSpaceOnUse">
              <path d="M14 0H0V14" fill="none" stroke="oklch(0.86 0.012 270)" strokeWidth="0.5"/>
            </pattern>
          </defs>
          <rect width="280" height="180" fill="url(#grid)"/>
          <path d="M30,150 C80,140 110,80 160,90 C210,100 230,40 260,35" stroke={accent} strokeWidth="2.4" fill="none" strokeLinecap="round" strokeDasharray="0 6 250 0"/>
          <circle cx="30"  cy="150" r="5" fill="#fff" stroke={accent} strokeWidth="2"/>
          <circle cx="160" cy="90"  r="4" fill={accent}/>
          <circle cx="260" cy="35"  r="5" fill={accent}/>
        </svg>
      </div>
      <div className="appscreen__map-card">
        <div>
          <div className="appscreen__hero-label">DXB → IST · Lane #1240</div>
          <div className="appscreen__hero-val" style={{ fontSize: 18 }}>ETA · 3d 04h</div>
        </div>
        <span className="appscreen__pill" style={{ color: accent, borderColor: accent }}>On time</span>
      </div>
    </div>
  );
}

function ScreenLesson({ accent }) {
  return (
    <div className="appscreen__body">
      <div className="appscreen__lesson-meta">CHAPTER 6 · ALGEBRA</div>
      <div className="appscreen__lesson-title">Quadratic equations</div>
      <div className="appscreen__lesson-frac" style={{ color: accent }}>
        x = <span className="appscreen__frac"><span>−b ± √(b² − 4ac)</span><span>2a</span></span>
      </div>
      <div className="appscreen__progress">
        <div className="appscreen__progress-fill" style={{ width: "68%", background: accent }}></div>
      </div>
      <div className="appscreen__caption">Section 4 of 6 · 12 min left</div>
    </div>
  );
}

function ScreenChat({ accent, app }) {
  const hue = app?.cover?.hue || 250;
  return (
    <div className="appscreen__body appscreen__chat">
      <div className="appscreen__bubble appscreen__bubble--in">Why does completing the square work?</div>
      <div className="appscreen__bubble appscreen__bubble--out" style={{ background: accent }}>
        It's a trick to turn any quadratic into a perfect square…
      </div>
      <div className="appscreen__bubble appscreen__bubble--in" style={{ background: `oklch(0.94 0.04 ${hue})` }}>Got it. Can you show me with x² + 6x + 4?</div>
      <div className="appscreen__typing">
        <span></span><span></span><span></span>
      </div>
    </div>
  );
}

function AppFrame({ app, screen, scale = 0.42 }) {
  return (
    <div className="app-frame" style={{ "--frame-scale": scale }}>
      <IOSDevice width={402} height={874} dark={false} title={app?.name || "App"}>
        <AppScreen kind={screen?.kind || "dashboard"} app={app} />
      </IOSDevice>
    </div>
  );
}

Object.assign(window, {
  AppIcon, StatusBadge, PlatformChips, Rating, StoreBadge,
  AppScreen, AppFrame,
  AppMarquee, PressStrip,
});

/* ============================================================
   <AppMarquee /> — auto-scrolling row of app icons (homepage).
   ============================================================ */

function AppMarquee() {
  const apps = window.APPS || [];
  if (!apps.length) return null;
  // Render two copies for a seamless loop.
  const doubled = [...apps, ...apps];
  return (
    <section className="app-marquee" aria-label="Apps from the Innoveev studio">
      <div className="container">
        <div className="app-marquee__head">
          <h2 className="app-marquee__title">
            Apps we ship, day after <em>day.</em>
          </h2>
          <a href="apps.html" className="app-marquee__cta">
            See every app <Arrow />
          </a>
        </div>
      </div>
      <div className="app-marquee__track" role="list">
        {doubled.map((app, i) => (
          <a
            key={`${app.slug}-${i}`}
            href={`app.html?slug=${app.slug}`}
            className="app-marquee__item"
            role="listitem"
            aria-label={app.name}
            data-cursor={app.name}
          >
            <AppIcon app={app} size={48} />
            <span>
              <span className="app-marquee__item-name" style={{ display: "block" }}>{app.name}</span>
              <span className="app-marquee__item-cat">{app.category}</span>
            </span>
          </a>
        ))}
      </div>
    </section>
  );
}

/* ============================================================
   <PressStrip /> — "As seen in" press logo row.
   ============================================================ */

const PRESS_LOGOS = [
  { name: "TechCrunch",     style: "sans"  },
  { name: "Wamda",          style: "serif" },
  { name: "Wired",          style: "sans"  },
  { name: "Khaleej Times",  style: "serif" },
  { name: "GITEX",          style: "mono"  },
  { name: "Gulf News",      style: "serif" },
  { name: "Skift",          style: "sans"  },
  { name: "Forbes Middle East", style: "serif" },
];

function PressStrip() {
  return (
    <section className="press-strip" aria-label="Press coverage">
      <div className="container">
        <div className="press-strip__label eyebrow eyebrow--no-rule">
          As seen in
        </div>
        <div className="press-strip__row">
          {PRESS_LOGOS.map((p) => (
            <span
              key={p.name}
              className={`press-strip__logo press-strip__logo--${p.style}`}
            >
              {p.name}
            </span>
          ))}
        </div>
      </div>
    </section>
  );
}
