/* ===== Payments, Reports, Team, Settings ===== */
const Dw = window.DATA;

// ---------- PAYMENTS ----------
function Payments() {
  const [tab, setTab] = useState("upcoming");
  const tabs = [{ id:"upcoming", label:"Upcoming" }, { id:"rules", label:"Automation rules" }, { id:"history", label:"History" }];
  const approvePay = async (id) => {
    try { if (window.ContaAPI) await window.ContaAPI.approvePayment(id); } catch (e) { console.error(e); }
  };
  return (
    <div className="view content-inner">
      <FilterBar tabs={tabs} active={tab} setActive={setTab}
        right={<button className="btn btn-accent"><Icon name="plus" size={15}/> New payment</button>}/>

      {tab==="rules" ? (
        <div className="grid" style={{ gridTemplateColumns:"1fr 1fr" }}>
          {Dw.paymentRules.map(rule => (
            <Card key={rule.id}>
              <div style={{ display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:12 }}>
                <div>
                  <div style={{ fontSize:14.5, fontWeight:600 }}>{rule.name}</div>
                  <div style={{ fontSize:13, color:"var(--text-2)", marginTop:4, lineHeight:1.5 }}>{rule.desc}</div>
                </div>
                <Toggle ruleId={rule.id} on={rule.on}/>
              </div>
              <div className="divider"></div>
              <div style={{ display:"flex", alignItems:"center", gap:8, fontSize:12.5, color:"var(--text-3)" }}>
                <Icon name="clock" size={15}/> {rule.runs}
              </div>
            </Card>
          ))}
        </div>
      ) : (
        <Card style={{ padding:0, overflow:"hidden" }}>
          <table className="tbl">
            <thead><tr><th style={{ paddingLeft:20 }}>Payee</th><th>Description</th><th>Due</th><th>Method</th><th>Status</th><th className="num" style={{ paddingRight:20 }}>Amount</th></tr></thead>
            <tbody>
              {Dw.payments.map(p => (
                <tr key={p.id} className="clickable">
                  <td style={{ paddingLeft:20, fontWeight:600 }}>
                    <span style={{ display:"inline-flex", alignItems:"center", gap:8 }}>
                      {p.recurring && <Icon name="clock" size={14} style={{ color:"var(--text-3)" }}/>}{p.payee}</span>
                  </td>
                  <td style={{ color:"var(--text-2)" }}>{p.desc}{p.flag && <div style={{ fontSize:11.5, color:"var(--neg)", marginTop:2 }}>⚑ {p.flag}</div>}</td>
                  <td style={{ whiteSpace:"nowrap" }}>{p.due}</td>
                  <td style={{ color:"var(--text-2)" }}>{p.method}</td>
                  <td><StatusBadge status={p.status}/></td>
                  <td className="num mono" style={{ paddingRight:20, fontWeight:600 }}>
                    {p.status==="needs-approval"
                      ? <span style={{ display:"inline-flex", flexDirection:"column", alignItems:"flex-end", gap:5 }}>
                          {Dw.eur(p.amount)}<button className="btn btn-accent" style={{ padding:"4px 10px", fontSize:12 }} onClick={(e) => { e.stopPropagation(); approvePay(p.id); }}>Approve</button></span>
                      : Dw.eur(p.amount)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}
    </div>
  );
}

function Toggle({ ruleId, on: initial }) {
  const [on, setOn] = useState(initial);
  const toggle = async () => {
    const next = !on;
    setOn(next);
    if (!ruleId) return;
    try {
      if (window.ContaAPI) await window.ContaAPI.togglePaymentRule(ruleId, next);
    } catch (e) {
      console.error(e);
      setOn(!next);
    }
  };
  return (
    <button onClick={toggle} style={{ width:42, height:24, borderRadius:99, padding:2, flex:"0 0 auto",
      background: on ? "var(--accent)" : "var(--line)", transition:"background .2s" }}>
      <span style={{ display:"block", width:20, height:20, borderRadius:"50%", background:"#fff",
        transform: on ? "translateX(18px)" : "none", transition:"transform .2s", boxShadow:"0 1px 2px rgba(0,0,0,.2)" }}></span>
    </button>
  );
}

// ---------- REPORTS ----------
function Reports() {
  const inc = Dw.cashflow.slice(-3).reduce((s,d)=>s+d.income,0);
  const exp = Dw.cashflow.slice(-3).reduce((s,d)=>s+d.expense,0);
  const pl = [
    { label:"Revenue", value: inc, bold:true },
    { label:"Cost of goods sold", value: -Math.round(exp*0.46), indent:true },
    { label:"Gross profit", value: inc - Math.round(exp*0.46), bold:true, rule:true },
    { label:"Payroll", value: -Math.round(exp*0.31), indent:true },
    { label:"Rent & utilities", value: -Math.round(exp*0.13), indent:true },
    { label:"Marketing", value: -Math.round(exp*0.06), indent:true },
    { label:"Other operating", value: -Math.round(exp*0.04), indent:true },
    { label:"Net profit", value: inc - exp, bold:true, rule:true, hl:true },
  ];
  return (
    <div className="view content-inner">
      <div style={{ display:"flex", alignItems:"center", gap:12, marginBottom:"var(--gap)" }}>
        <div className="seg"><button className="on">P&amp;L</button><button>Expenses</button><button>Cash flow</button><button>VAT</button></div>
        <div style={{ flex:1 }}></div>
        <button className="btn"><Icon name="doc" size={15}/> Export PDF</button>
        <button className="btn btn-primary"><Icon name="arrowDownRight" size={15}/> Export CSV</button>
      </div>
      <div className="grid" style={{ gridTemplateColumns:"1.3fr 1fr" }}>
        <Card title="Profit & Loss" sub="Last quarter · Mar–May 2026">
          <table className="tbl" style={{ marginTop:4 }}>
            <tbody>
              {pl.map((r,i) => (
                <tr key={i} style={{ borderTop: r.rule ? "1.5px solid var(--line)" : "none" }}>
                  <td style={{ paddingLeft: r.indent?28:14, fontWeight: r.bold?600:400, border:"none",
                    color: r.indent?"var(--text-2)":"var(--text)", fontSize: r.hl?15:13.5 }}>{r.label}</td>
                  <td className="num mono" style={{ paddingRight:14, fontWeight: r.bold?700:500, border:"none",
                    color: r.hl?"var(--accent-ink)":(r.value<0?"var(--text-2)":"var(--text)"), fontSize: r.hl?15:13.5 }}>
                    {r.value<0?"−":""}{Dw.eur0(Math.abs(r.value))}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
        <div className="grid">
          <Card title="Margin">
            <div className="kpi-value" style={{ marginTop:0 }}><AnimatedNumber value={25.8} format={n=>n.toFixed(1)+"%"}/></div>
            <Delta v={2.3} suffix="vs prior quarter"/>
          </Card>
          <Card title="Expense mix" sub="This quarter">
            <DonutChart data={Dw.expenseCats} eur0={Dw.eur0} size={140}/>
          </Card>
        </div>
      </div>
    </div>
  );
}

// ---------- TEAM ----------
function Team() {
  return (
    <div className="view content-inner">
      <div style={{ display:"flex", alignItems:"center", marginBottom:"var(--gap)" }}>
        <div><div style={{ fontWeight:600, fontSize:15 }}>Team & roles</div>
          <div style={{ fontSize:13, color:"var(--text-3)" }}>{Dw.team.length} members · role-based access</div></div>
        <div className="avatar-group" style={{ marginLeft:18 }}>
          {Dw.team.map((m,i) => (
            <span key={i} className="avatar ag" title={m.name} style={{ width:36, height:36, fontSize:13, background:m.color }}>{m.initials}</span>
          ))}
        </div>
        <div style={{ flex:1 }}></div>
        <button className="btn btn-accent"><Icon name="plus" size={15}/> Invite member</button>
      </div>
      <Card style={{ padding:0, overflow:"hidden" }}>
        <table className="tbl">
          <thead><tr><th style={{ paddingLeft:20 }}>Member</th><th>Email</th><th>Role</th><th>Access</th><th></th></tr></thead>
          <tbody>
            {Dw.team.map((m,i) => (
              <tr key={i} className="clickable">
                <td style={{ paddingLeft:20 }}>
                  <span style={{ display:"inline-flex", alignItems:"center", gap:11 }}>
                    <span className="avatar" style={{ width:34, height:34, fontSize:12.5, background:m.color }}>{m.initials}</span>
                    <b>{m.name}</b></span>
                </td>
                <td style={{ color:"var(--text-2)" }}>{m.email}</td>
                <td><Badge kind={i===0?"pos":"neutral"}>{m.role}</Badge></td>
                <td style={{ color:"var(--text-2)", fontSize:12.5 }}>
                  {m.role.includes("Owner") ? "Full access · billing · team"
                    : m.role==="Accountant" ? "Full financial · approve · reports"
                    : m.role==="Manager" ? "Dashboards · approve · reports"
                    : "Submit receipts · own items"}</td>
                <td className="num" style={{ paddingRight:20 }}><Icon name="dots" size={18} style={{ color:"var(--text-3)" }}/></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ---------- SETTINGS ----------
function Settings({ org }) {
  const [tab, setTab] = useState("profile");
  const tabs = [{ id:"profile", label:"Business profile" }, { id:"integrations", label:"Integrations" }, { id:"widgets", label:"Dashboard" }, { id:"features", label:"Feature flags" }];
  return (
    <div className="view content-inner">
      <FilterBar tabs={tabs} active={tab} setActive={setTab}/>
      {tab==="profile" && (
        <div className="grid" style={{ gridTemplateColumns:"1fr 1fr" }}>
          <Card title="Business profile">
            <div className="field"><label>Business name</label><input className="ipt" defaultValue={org.name}/></div>
            <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:12 }}>
              <div className="field"><label>Business type</label>
                <select className="ipt" defaultValue={org.type}>
                  {Object.entries(Dw.businessTypes).map(([k,v]) => <option key={k} value={k}>{v.label}</option>)}
                </select></div>
              <div className="field"><label>Currency</label><select className="ipt"><option>EUR €</option><option>USD $</option><option>GBP £</option></select></div>
            </div>
            <div className="field"><label>Timezone</label><input className="ipt" defaultValue="Europe/Rome (CET)"/></div>
          </Card>
          <Card title="Branding" sub="Logo & business image — shown on your dashboard">
            <div style={{ display:"flex", gap:16 }}>
              <div style={{ flex:"0 0 auto", textAlign:"center" }}>
                <div className="brand-logo-badge" style={{ margin:0, width:80, height:80 }}>
                  <img src="assets/bull.png" alt="" className="brand-on-light" style={{ width:52, height:52, objectFit:"contain" }}/>
                </div>
                <button className="btn" style={{ marginTop:10, fontSize:12, padding:"6px 11px" }}><Icon name="upload" size={13}/> Logo</button>
              </div>
              <div style={{ flex:1 }}>
                <div className="ph" style={{ height:96, borderRadius:12, position:"relative" }}><span className="ph-label">Business image</span></div>
                <button className="btn" style={{ marginTop:10, fontSize:12, padding:"6px 11px" }}><Icon name="upload" size={13}/> Replace image</button>
              </div>
            </div>
            <div className="divider"></div>
            <div className="field" style={{ marginBottom:0 }}><label>Accent color</label>
              <div style={{ display:"flex", gap:8 }}>
                {["#456882","#242d3c","#5a7390","#70879f"].map(c => (
                  <span key={c} style={{ width:30, height:30, borderRadius:8, background:c, cursor:"pointer",
                    outline: c==="#456882"?"2px solid var(--text)":"none", outlineOffset:2 }}></span>
                ))}
                <span style={{ fontSize:12, color:"var(--text-3)", alignSelf:"center", marginLeft:6 }}>Change live in the Tweaks panel →</span>
              </div>
            </div>
          </Card>
        </div>
      )}
      {tab==="integrations" && (
        <div className="grid" style={{ gridTemplateColumns:"repeat(3,1fr)" }}>
          {Dw.integrations.map((it,i) => (
            <Card key={i}>
              <div style={{ display:"flex", alignItems:"center", gap:11, marginBottom:12 }}>
                <div className="rico" style={{ width:42, height:42 }}><Icon name={it.icon} size={20}/></div>
                <div><div style={{ fontWeight:600, fontSize:14 }}>{it.name}</div><div style={{ fontSize:11.5, color:"var(--text-3)" }}>{it.cat}</div></div>
              </div>
              <div style={{ fontSize:13, color:"var(--text-2)", minHeight:38 }}>{it.desc}</div>
              <button className="btn" style={{ width:"100%", justifyContent:"center", marginTop:6,
                ...(it.connected ? {} : { background:"var(--navy)", color:"#fff", borderColor:"var(--navy)" }) }}>
                {it.connected ? <><span className="bdot" style={{ width:7, height:7, borderRadius:"50%", background:"var(--pos)" }}></span> Connected</> : "Connect"}
              </button>
            </Card>
          ))}
        </div>
      )}
      {tab==="widgets" && (
        <Card title="Dashboard widgets" sub="Per-business-type defaults · drag to rearrange (Owner & Manager)">
          <div className="grid" style={{ gridTemplateColumns:"repeat(2,1fr)" }}>
            {["Brand header","KPI overview","Cash flow chart","Expense breakdown","Recent transactions","Receipts to review","Upcoming payments","AI insight"].map((w,i) => (
              <div key={i} className="row" style={{ padding:"12px 14px", border:"1px solid var(--line)", borderRadius:10, background:"var(--surface-2)" }}>
                <Icon name="grid" size={16} style={{ color:"var(--text-3)" }}/>
                <div className="r-main"><div className="r-title">{w}</div></div>
                <Toggle on={true}/>
              </div>
            ))}
          </div>
        </Card>
      )}
      {tab==="features" && (
        <Card title="Feature flags" sub="Per-organization module toggles">
          {[["Receipt OCR extraction",true],["AI accountant assistant",true],["Payment automation",true],["Multi-currency",false],["E-invoicing (SdI)",false],["Inventory tracking",false]].map(([f,on],i) => (
            <div key={i} className="row">
              <div className="r-main"><div className="r-title">{f}</div></div>
              <Toggle on={on}/>
            </div>
          ))}
        </Card>
      )}
    </div>
  );
}

Object.assign(window, { Payments, Reports, Team, Settings, Toggle });
