// Profile, General (org/project), Cost Analytics, Files, Integrations, SSH Key — lighter screens.

const ProfileScreen = ({ data, setData }) => {
  const [form, setForm] = React.useState(data.profile);
  return (
    <div className="hx-screen">
      <ScreenHeader icon={<IconUser size={20}/>} title="Profile" subtitle="Personal account details and preferences." />
      <Card title="Account">
        <div className="hx-form-row"><Avatar name={form.name} size={64}/><div><div style={{fontWeight:600}}>{form.name}</div><div style={{color:"var(--muted)",fontSize:13}}>{form.email}</div><div style={{marginTop:8}}><Btn kind="secondary" size="sm">Change photo</Btn></div></div></div>
        <FormField label="Full name"><Input value={form.name} onChange={e=>setForm({...form, name:e.target.value})}/></FormField>
        <FormField label="Email"><Input value={form.email} onChange={e=>setForm({...form, email:e.target.value})}/></FormField>
        <FormField label="Username" hint="Used in resource paths and the URL of your projects."><Input value={form.username} onChange={e=>setForm({...form, username:e.target.value})}/></FormField>
        <FormField label="Time zone"><Input value={form.tz} onChange={e=>setForm({...form, tz:e.target.value})}/></FormField>
        <div style={{display:"flex",gap:8,marginTop:18}}>
          <Btn kind="primary" onClick={()=>{setData(d=>({...d,profile:form})); window.__toast("Profile saved");}}>Save changes</Btn>
          <Btn kind="secondary" onClick={()=>setForm(data.profile)}>Cancel</Btn>
        </div>
      </Card>
      <Card title="Danger zone" subtitle="Permanent account actions.">
        <DangerZone
          title="Delete account"
          description="Permanently remove your account and all data. This cannot be undone."
          actionLabel="Delete account"
          confirmPhrase="delete my account"
          onConfirm={() => window.__toast("Account deletion requested (demo)")}
        />
      </Card>
      <style>{`
        .hx-form-row { display:flex; gap: 18px; align-items: center; margin-bottom: 22px; }
        .hx-danger-row { display:flex; justify-content:space-between; align-items:center; gap: 16px; }
      `}</style>
    </div>
  );
};

const GeneralOrgScreen = ({ data }) => (
  <div className="hx-screen">
    <ScreenHeader icon={<IconBuilding size={20}/>} title="General" subtitle="Organization settings and metadata." />
    <Card title="Organization">
      <FormField label="Organization name"><Input defaultValue={data.org.name}/></FormField>
      <FormField label="Organization ID"><Input defaultValue={data.org.id} readOnly suffix={<IconCopy size={14}/>}/></FormField>
      <FormField label="Industry"><Input defaultValue="Software / AI"/></FormField>
      <FormField label="Country"><Input defaultValue="India"/></FormField>
      <div style={{marginTop:14}}><Btn kind="primary">Save changes</Btn></div>
    </Card>
    <Card title="Usage limits" subtitle="Spend caps and per-project limits for the organization.">
      <div className="hx-limit-grid">
        <LimitRow label="Monthly spend cap" value="$2,500.00" sub="Resets on the 1st of each month."/>
        <LimitRow label="Per-project soft limit" value="$500.00" sub="Warns project members past this threshold."/>
        <LimitRow label="GPU hours / month" value="1,200 hrs" sub="Across all clusters in the org."/>
      </div>
    </Card>
    <style>{`
      .hx-limit-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }
    `}</style>
  </div>
);

const LimitRow = ({label,value,sub}) => (
  <div style={{border:"1px solid var(--line)",borderRadius:10,padding:"14px 16px",background:"var(--panel-2)"}}>
    <div style={{color:"var(--muted)",fontSize:12.5,fontWeight:500,letterSpacing:".02em",textTransform:"uppercase"}}>{label}</div>
    <div style={{fontSize:22,fontWeight:600,letterSpacing:"-.01em",marginTop:8,fontFeatureSettings:'"tnum"'}}>{value}</div>
    <div style={{color:"var(--muted)",fontSize:12,marginTop:6}}>{sub}</div>
  </div>
);

const GeneralProjectScreen = ({ data }) => (
  <div className="hx-screen">
    <ScreenHeader icon={<IconFolder size={20}/>} title="General" subtitle={`Project settings for ${data.currentProject}.`}/>
    <Card title="Project">
      <FormField label="Project name"><Input defaultValue={data.currentProject}/></FormField>
      <FormField label="Project ID"><Input defaultValue="proj_8e1f3a2c" readOnly suffix={<IconCopy size={14}/>}/></FormField>
      <FormField label="Description"><Input defaultValue="Inference experiments and finetune jobs."/></FormField>
      <FormField label="Default model"><Input defaultValue="helix-7b-instruct"/></FormField>
      <div style={{marginTop:14}}><Btn kind="primary">Save changes</Btn></div>
    </Card>
  </div>
);

const CostAnalyticsScreen = ({ data }) => {
  const days = data.spendByDay;
  const [period, setPeriod] = React.useState("30d");
  const totalMo = days.reduce((s, v) => s + v, 0);
  const topModels = data.spendByModel;
  const palette = ["var(--accent)", "#0fb67e", "#e8a93b", "#d63a8a", "#9aa1ad"];
  return (
    <div className="hx-screen">
      <ScreenHeader icon={<IconChart size={20}/>} title="Cost Analytics" subtitle="Detailed organization-level spend breakdown." />
      <div className="hx-card-grid hx-3">
        <StatCard label="Total this month"      value={fmt.currency(totalMo)}    delta="+18.3%"             deltaTone="warn"    trend={days.slice(-14)}/>
        <StatCard label="Forecasted month-end"  value={fmt.currency(1210.40)}    delta="vs $980 last month" deltaTone="neutral" trend={days.slice(-14).map(v => v * 1.4)}/>
        <StatCard label="Top model"             value="helix-70b"                delta="34% of spend"       deltaTone="accent"/>
      </div>
      <Card title="Spend, last 30 days"
            subtitle="Daily inference and GPU usage."
            action={<SegmentedControl size="sm" value={period} onChange={setPeriod} options={[{label:"7d",value:"7d"},{label:"30d",value:"30d"},{label:"90d",value:"90d"}]}/>}>
        <LineChart
          data={period === "7d" ? days.slice(-7) : period === "30d" ? days : [...days, ...days.slice(0, 60)].slice(0, 90)}
          height={260}
          formatValue={(v) => "$" + v.toFixed(0)}
          axisLabels={period === "7d" ? ["7d ago","","Today"] : period === "30d" ? ["30d ago","15d ago","Today"] : ["90d ago","45d ago","Today"]}
        />
      </Card>
      <div className="hx-card-grid hx-2">
        <Card title="Spend by model" subtitle="Proportions for this billing cycle.">
          <DonutChart
            size={180} thickness={22}
            data={topModels.map((m, i) => ({ label: m.model, value: m.spend, color: palette[i % palette.length] }))}
            centerValue={fmt.currency(topModels.reduce((s, m) => s + m.spend, 0))}
            centerLabel="this month"
            formatValue={(v) => "$" + v.toFixed(0)}
          />
        </Card>
        <Card title="Budget utilization" subtitle="Soft caps configured in Org → Usage limits.">
          <div style={{display:"flex",flexDirection:"column",gap:16}}>
            <ProgressBar value={totalMo} max={2500} label="Monthly spend cap" sub="$2,500.00 / month" tone={totalMo > 2000 ? "warn" : "accent"} format={(v) => "$" + v.toFixed(0)}/>
            <ProgressBar value={780}     max={1200} label="GPU hours / month" sub="Resets on the 1st" tone="accent" format={(v) => v + " hrs"}/>
            <ProgressBar value={48}      max={50}   label="Concurrent workers" sub="Approaching limit" tone="bad" format={(v) => v + ""}/>
          </div>
        </Card>
      </div>
      <Card title="Spend by model" subtitle="Click any column header to sort." padded={false}>
        <DataTable
          rows={data.spendByModel.map((m, i) => ({ ...m, id: m.model, rank: i + 1 }))}
          keyField="id"
          defaultSort={{ key: "spend", dir: "desc" }}
          columns={[
            { key:"model", label:"Model",
              render:(r)=><span style={{display:"inline-flex",gap:8,alignItems:"center"}}><span style={{display:"inline-block",width:8,height:8,borderRadius:2,background:palette[(r.rank-1) % palette.length]}}/><span style={{fontFamily:"var(--mono)",fontSize:12.5}}>{r.model}</span></span> },
            { key:"requests", label:"Requests", w:140, align:"right", mono: true },
            { key:"tokens",   label:"Tokens",   w:160, align:"right", mono: true },
            { key:"spend",    label:"Spend",    w:130, align:"right", mono: true,
              render:(r)=>"$"+r.spend.toFixed(2) },
          ]}
        />
      </Card>
    </div>
  );
};

const StatBlock = ({label,value,delta,tone}) => (
  <Card>
    <div style={{color:"var(--muted)",fontSize:13,fontWeight:500}}>{label}</div>
    <div style={{fontSize:30,fontWeight:600,letterSpacing:"-.02em",marginTop:10,fontFeatureSettings:'"tnum"'}}>{value}</div>
    <div style={{marginTop:8}}><Pill tone={tone}>{delta}</Pill></div>
  </Card>
);

const FilesScreen = ({ data }) => (
  <div className="hx-screen">
    <ScreenHeader icon={<IconUpload size={20}/>} title="Files" subtitle="Datasets and artifacts uploaded for finetuning and batch jobs." />
    <Toolbar
      actions={<Btn kind="primary" icon={<IconUpload size={14}/>} onClick={() => window.__nav("upload-file")}>Upload file</Btn>}
      searchPlaceholder="Search files" onSearchChange={() => {}}
    />
    <Card padded={false}>
      <Table
        columns={[
          { key:"name", label:"Name", render:(r)=><span style={{display:"inline-flex",gap:8,alignItems:"center"}}><IconFile size={14}/><span style={{fontWeight:500}}>{r.name}</span></span> },
          { key:"purpose", label:"Purpose", w:160, render:(r)=><Pill tone="neutral">{r.purpose}</Pill> },
          { key:"size", label:"Size", w:110, align:"right" },
          { key:"created", label:"Uploaded", w:160 },
          { key:"action", label:"", w:60, align:"right", render:()=><button className="hx-icon-btn" aria-label="More"><IconMore size={14}/></button> },
        ]}
        rows={data.files}
      />
    </Card>
  </div>
);

const IntegrationsScreen = ({ data }) => (
  <div className="hx-screen">
    <ScreenHeader icon={<IconPlug size={20}/>} title="Integrations" subtitle={`Connect ${window.APP_CONFIG.brand.productName} to your existing tools and workflows.`} />
    <div className="hx-int-grid">
      {data.integrations.map(it => (
        <div className="hx-int-card" key={it.name}>
          <div className="hx-int-head">
            <div className="hx-int-logo" style={{background: it.color}}>{it.name[0]}</div>
            <div style={{flex:1}}>
              <div style={{fontWeight:600}}>{it.name}</div>
              <div style={{color:"var(--muted)",fontSize:12.5,marginTop:2}}>{it.desc}</div>
            </div>
            {it.connected ? <Pill tone="good">Connected</Pill> : null}
          </div>
          <div className="hx-int-foot">
            {it.connected
              ? <Btn kind="secondary" size="sm">Manage</Btn>
              : <Btn kind="primary" size="sm">Connect</Btn>}
            <Btn kind="ghost" size="sm" iconRight={<IconExternal size={12}/>}>Docs</Btn>
          </div>
        </div>
      ))}
    </div>
    <style>{`
      .hx-int-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 14px; }
      .hx-int-card { background: var(--panel); border: 1px solid var(--line); border-radius: var(--r-md); padding: 16px; box-shadow: var(--shadow-1); display:flex; flex-direction:column; gap: 14px; }
      .hx-int-head { display:flex; gap: 12px; align-items: flex-start; }
      .hx-int-logo { width: 36px; height: 36px; border-radius: 8px; display:flex; align-items:center; justify-content:center; color: white; font-weight: 700; font-size: 18px; }
      .hx-int-foot { display:flex; gap: 6px; justify-content: space-between; }
    `}</style>
  </div>
);

const SshKeyScreen = ({ data }) => (
  <div className="hx-screen">
    <ScreenHeader icon={<IconKey size={20}/>} title="SSH Key" subtitle="Public keys authorized for GPU cluster access." />
    <Toolbar actions={<Btn kind="primary" icon={<IconPlus size={14}/>} onClick={() => window.__nav("new-ssh-key")}>Add SSH key</Btn>}/>
    <Card padded={false}>
      <Table
        columns={[
          { key:"label", label:"Label", render:(r)=><span style={{fontWeight:500}}>{r.label}</span> },
          { key:"fingerprint", label:"Fingerprint", render:(r)=><span style={{fontFamily:"var(--mono)",fontSize:12}}>{r.fp}</span> },
          { key:"added", label:"Added", w:140 },
          { key:"action", label:"", w:60, align:"right", render:()=><button className="hx-icon-btn" aria-label="Remove"><IconTrash size={14}/></button> },
        ]}
        rows={data.sshKeys}
      />
    </Card>
  </div>
);

Object.assign(window, {
  ProfileScreen, GeneralOrgScreen, GeneralProjectScreen,
  CostAnalyticsScreen, FilesScreen, IntegrationsScreen, SshKeyScreen,
});
