/* ============ Plan & Usage (Admin → Setting) ============
   Usage-based billing dashboard. Three metered dimensions:
     • Users (all roles)           • Projects (incl. archived)
     • Cloud Storage (R2)
   Entities are unlimited (no per-entity charge).
   Read-only by design — plan changes are handled by the account manager,
   so there is no self-serve adjust / pricing here. */

/* Customer's current allocation (mock — provisioned by the account manager).
   Storage has no live aggregate in the prototype, so it is mocked too. */
const PLAN_LIMITS    = { users: 15, projects: 25, storageGb: 50 };
const STORAGE_USED_GB = 31.5;

/* Categorical palette tokens, cycled for breakdown segments */
const SEG_COLORS = ["var(--seg-1)","var(--seg-2)","var(--seg-3)","var(--seg-4)","var(--seg-5)","var(--seg-6)","var(--seg-7)"];

/* Pick a semantic tone from a usage percentage */
const usageTone = (pct) => pct >= 90 ? "danger" : pct >= 75 ? "warn" : "ok";

/* One metered dimension card.
   `segments` (optional): [{ label, count, color }] → renders a stacked bar +
   legend broken down by category. Without it, a single-tone usage bar. */
const UsageMeter = ({ icon, label, used, limit, unit, caption, segments, maxSegments = 6 }) => {
  const pct  = limit ? Math.min(100, Math.round((used / limit) * 100)) : 0;
  const tone = usageTone(pct);

  /* Keep the card compact regardless of category count (e.g. 50 entities):
     show the top (maxSegments-1) and roll the rest into one "Others" piece. */
  let segs = segments;
  if (segments && segments.length > maxSegments) {
    const head = segments.slice(0, maxSegments - 1);
    const rest = segments.slice(maxSegments - 1);
    segs = [...head, {
      label: `+${rest.length} more`,
      count: rest.reduce((sum, s) => sum + s.count, 0),
      color: "var(--archive)",
    }];
  }
  return (
    <div className="card">
      <div className="card-body" style={{display:"flex",flexDirection:"column",gap:12}}>
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          <span style={{width:30,height:30,borderRadius:8,background:"var(--panel-2)",color:"var(--ink-2)",display:"grid",placeItems:"center",flexShrink:0}}>
            <Icon n={icon} s={15}/>
          </span>
          <span style={{fontSize:12.5,fontWeight:600,color:"var(--ink)"}}>{label}</span>
          <span style={{marginLeft:"auto"}} className={`sbadge ${tone === "danger" ? "danger" : tone === "warn" ? "warn" : "ok"}`}>{pct}%</span>
        </div>

        <div style={{display:"flex",alignItems:"baseline",gap:6}}>
          <span className="mono" style={{fontSize:24,fontWeight:600,letterSpacing:"-.01em",color:"var(--ink)"}}>{used}</span>
          <span className="mono" style={{fontSize:13,color:"var(--muted)"}}>/ {limit}{unit ? " " + unit : ""}</span>
        </div>

        <div className="meter">
          {segs
            ? segs.map((s,i) => (
                <div key={i} className="meter-seg"
                     style={{width:`${limit ? (s.count / limit) * 100 : 0}%`, background:s.color}}
                     title={`${s.label}: ${s.count}`}/>
              ))
            : <div className={`meter-fill ${tone}`} style={{width:`${pct}%`}}/>}
        </div>

        {segs && (
          <div className="seg-legend">
            {segs.map((s,i) => (
              <span key={i} className="seg-item">
                <span className="seg-dot" style={{background:s.color}}/>
                {s.label} <span className="seg-n">{s.count}</span>
              </span>
            ))}
          </div>
        )}

        {caption && <div style={{fontSize:11.5,color:"var(--muted)"}}>{caption}</div>}
      </div>
    </div>
  );
};

const PlanUsageScreen = ({ state, nav }) => {
  /* ---- Users (all roles) — broken down by role ---- */
  const allUsers     = (typeof USERS !== "undefined" ? USERS : []);
  const userTotal    = allUsers.length;
  const userInactive = allUsers.filter(u => u.active === false).length;
  const ROLE_ORDER   = ["Admin", "Supervisor", "Staff", "Guest"];
  const userSegments = ROLE_ORDER
    .map((role, i) => ({ label: role, count: allUsers.filter(u => u.role === role).length, color: SEG_COLORS[i] }))
    .filter(s => s.count > 0);

  /* ---- Projects (incl. archived) — broken down by entity ---- */
  const projects     = state.projects || [];
  const projTotal    = projects.length;
  const projActive   = projects.filter(p => p.status === "active").length;
  const projArchived = projects.filter(p => p.status === "archived").length;
  const projDraft    = projTotal - projActive - projArchived;
  /* group by entity, biggest first, label by entity code */
  const byEntity = {};
  projects.forEach(p => { byEntity[p.entityId] = (byEntity[p.entityId] || 0) + 1; });
  const projSegments = Object.entries(byEntity)
    .sort((a,b) => b[1] - a[1])
    .map(([eid, count], i) => ({ label: (typeof entityById === "function" ? entityById(eid)?.code : null) || eid, count, color: SEG_COLORS[i % SEG_COLORS.length] }));

  /* ---- Entities (unlimited) ---- */
  const entityTotal  = (state.entities || []).length;

  return (
    <>
      <div className="page-head">
        <div className="page-title-row">
          <h1 className="page-title">Usage</h1>
        </div>
      </div>

      <div className="page-body">
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(260px, 1fr))",gap:14}}>
          <UsageMeter
            icon="users" label="Users"
            used={userTotal} limit={PLAN_LIMITS.users}
            segments={userSegments}
            caption={`Counts every role · ${userInactive} inactive seat${userInactive === 1 ? "" : "s"}`}/>

          <UsageMeter
            icon="layers" label="Projects"
            used={projTotal} limit={PLAN_LIMITS.projects}
            segments={projSegments}
            caption={`${projActive} active · ${projArchived} archived · ${projDraft} draft`}/>

          <UsageMeter
            icon="database" label="Cloud Storage"
            used={STORAGE_USED_GB} limit={PLAN_LIMITS.storageGb} unit="GB"
            caption={`R2 object storage across all projects`}/>

          {/* Entities — unlimited, no per-entity charge */}
          <div className="card">
            <div className="card-body" style={{display:"flex",flexDirection:"column",gap:12}}>
              <div style={{display:"flex",alignItems:"center",gap:8}}>
                <span style={{width:30,height:30,borderRadius:8,background:"var(--panel-2)",color:"var(--ink-2)",display:"grid",placeItems:"center",flexShrink:0}}>
                  <Icon n="building" s={15}/>
                </span>
                <span style={{fontSize:12.5,fontWeight:600,color:"var(--ink)"}}>Entities</span>
                <span style={{marginLeft:"auto"}} className="sbadge accent">Unlimited</span>
              </div>

              <div style={{display:"flex",alignItems:"baseline",gap:6}}>
                <span className="mono" style={{fontSize:24,fontWeight:600,letterSpacing:"-.01em",color:"var(--ink)"}}>{entityTotal}</span>
                <span className="mono" style={{fontSize:13,color:"var(--muted)"}}>clients</span>
              </div>

              <div className="meter">
                <div className="meter-fill unlim" style={{width:"100%"}}/>
              </div>

              <div style={{fontSize:11.5,color:"var(--muted)"}}>No limit — entities are not metered</div>
            </div>
          </div>
        </div>

        {/* Plan changes are manual — handled by the account manager */}
        <div className="banner muted" style={{marginTop:16}}>
          <div className="b-ico"><Icon n="info" s={15}/></div>
          <div className="b-body">
            <span className="b-title">Need a higher limit?</span>
            Plan changes are handled by your account manager — you can raise <b>users</b>, <b>projects</b>, or <b>storage</b> independently. <a href="mailto:support@tumweb.co.th?subject=Plan%20limit%20increase" style={{color:"var(--accent-ink)",fontWeight:500}}>Contact us</a> to adjust your allocation.
          </div>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { PlanUsageScreen });
