// Database — Visual database builder
function ModuleDB() {
  const [view, setView] = React.useState('table');
  const D = KS_DATA;

  const statusPill = (s) => {
    const map = {
      'Open':      'info',
      'In Review': 'warn',
      'Resolved':  'ok',
      'Escalated': 'err',
    };
    return map[s] || '';
  };

  return (
    <div className="ks-module"
         style={{'--mod-current':'var(--mod-db)', '--mod-current-tint':'var(--mod-db-tint)'}}
         data-screen-label="db">
      <div style={{padding:'8px 16px', background:'var(--white)', borderBottom:'1px solid var(--ink-150)', display:'flex', alignItems:'center', gap:12}}>
        <div style={{width:28, height:28, borderRadius:6, background: 'var(--mod-db)', color:'white', display:'grid', placeItems:'center', fontWeight:700, fontSize:12}}>D</div>
        <div className="col" style={{lineHeight:1.2}}>
          <div style={{fontWeight:600, fontSize:13.5}}>Grievance Redressal — Case Registry</div>
          <div className="muted text-xs">PostgreSQL 16 · 5 tables · 240,793 rows · <span style={{color:'var(--ok)'}}>Healthy</span></div>
        </div>
        <div className="grow"/>
        <button className="btn">Backup</button>
        <button className="btn">Deploy</button>
        <button className="btn primary">{IC.share} Share</button>
      </div>

      <div style={{flex:1, display:'flex', overflow:'hidden'}}>
        {/* Sidebar: tables */}
        <div style={{width:240, background:'var(--white)', borderRight:'1px solid var(--ink-150)', padding:'14px 10px', overflow:'auto'}}>
          <div className="row" style={{padding:'0 6px 8px'}}>
            <div style={{fontSize:10.5, fontWeight:600, color:'var(--ink-500)', letterSpacing:'0.08em', textTransform:'uppercase'}}>Tables</div>
            <div className="grow"/>
            <button className="ks-icon-btn" style={{height:22, width:22}}>{IC.plus}</button>
          </div>
          {D.dbTables.map(t => (
            <button key={t.name} style={{
              width:'100%', display:'flex', alignItems:'center', gap:8,
              padding:'7px 10px', border:'none',
              background: t.active ? 'var(--mod-db-tint)' : 'transparent',
              color: t.active ? 'var(--mod-db)' : 'var(--ink-700)',
              borderRadius:6, fontSize:13, textAlign:'left',
              fontWeight: t.active ? 550 : 400,
              fontFamily:'var(--f-mono)',
              marginBottom: 2,
            }}>
              {IC.db}
              <span className="grow" style={{overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{t.name}</span>
              <span className="text-xs" style={{color:'var(--ink-500)'}}>{t.rows.toLocaleString('en-IN')}</span>
            </button>
          ))}

          <div style={{fontSize:10.5, fontWeight:600, color:'var(--ink-500)', letterSpacing:'0.08em', textTransform:'uppercase', padding:'14px 6px 6px'}}>Views</div>
          {['High-priority open', 'SLA breach — last 30d', 'By department (agg.)'].map(v => (
            <button key={v} style={{
              width:'100%', display:'flex', alignItems:'center', gap:8,
              padding:'6px 10px', border:'none', background:'transparent',
              borderRadius:5, fontSize:12.5, textAlign:'left',
              color:'var(--ink-700)',
            }}>
              {IC.eye}
              <span className="grow" style={{overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{v}</span>
            </button>
          ))}

          <div style={{fontSize:10.5, fontWeight:600, color:'var(--ink-500)', letterSpacing:'0.08em', textTransform:'uppercase', padding:'14px 6px 6px'}}>Forms</div>
          {['New grievance', 'Escalation form', 'Resolution notes'].map(v => (
            <button key={v} style={{
              width:'100%', display:'flex', alignItems:'center', gap:8,
              padding:'6px 10px', border:'none', background:'transparent',
              borderRadius:5, fontSize:12.5, textAlign:'left',
              color:'var(--ink-700)',
            }}>
              {IC.fileText}
              <span className="grow" style={{overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{v}</span>
            </button>
          ))}
        </div>

        {/* Main */}
        <div style={{flex:1, display:'flex', flexDirection:'column', overflow:'hidden'}}>
          {/* Tab bar */}
          <div style={{
            borderBottom:'1px solid var(--ink-150)',
            background:'var(--white)',
            padding: '0 12px',
            display:'flex', alignItems:'center', gap: 2,
          }}>
            {[
              {id:'table', l:'Table', ic:'table'},
              {id:'query', l:'Query', ic:'formula'},
              {id:'form',  l:'Form',  ic:'fileText'},
              {id:'schema',l:'Schema',ic:'db'},
            ].map(v => (
              <button key={v.id} onClick={()=>setView(v.id)}
                      style={{
                        padding: '10px 14px',
                        border:'none', background:'transparent',
                        fontSize: 12.5,
                        fontWeight: view === v.id ? 600 : 500,
                        color: view === v.id ? 'var(--mod-db)' : 'var(--ink-600)',
                        borderBottom: view === v.id ? '2px solid var(--mod-db)' : '2px solid transparent',
                        display:'flex', alignItems:'center', gap:6,
                      }}>
                {IC[v.ic]} {v.l}
              </button>
            ))}
            <div className="grow"/>
            <div className="row gap-2" style={{padding:'6px 0'}}>
              <button className="btn ghost text-sm">{IC.filter} Filter</button>
              <button className="btn ghost text-sm">{IC.sort} Sort</button>
              <button className="btn ai text-sm">{IC.sparkles} Ask in English</button>
              <button className="btn primary text-sm">{IC.plus} New row</button>
            </div>
          </div>

          {view === 'table' && (
            <div style={{flex:1, overflow:'auto', background:'var(--white)'}}>
              <table className="ks-table" style={{fontSize:13}}>
                <thead>
                  <tr>
                    <th style={{width:34}}><input type="checkbox"/></th>
                    <th>Case ID</th>
                    <th>Citizen</th>
                    <th>Category</th>
                    <th>Status</th>
                    <th>Priority</th>
                    <th>Filed</th>
                    <th>Department</th>
                    <th style={{width:40}}></th>
                  </tr>
                </thead>
                <tbody>
                  {D.dbGrievances.map((row, i) => (
                    <tr key={i}>
                      <td><input type="checkbox"/></td>
                      <td className="mono" style={{fontWeight:600, color:'var(--mod-db)'}}>{row[0]}</td>
                      <td>{row[1]}</td>
                      <td>{row[2]}</td>
                      <td><span className={"chip " + statusPill(row[3])} style={{fontSize:11}}>{row[3]}</span></td>
                      <td>
                        {row[4] === 'High' && <span style={{color:'var(--err)', fontWeight:600}}>● High</span>}
                        {row[4] === 'Med' && <span style={{color:'var(--warn)', fontWeight:600}}>● Med</span>}
                        {row[4] === 'Low' && <span style={{color:'var(--ink-500)', fontWeight:600}}>● Low</span>}
                      </td>
                      <td className="mono text-xs">{row[5]}</td>
                      <td className="muted">{row[6]}</td>
                      <td><button className="ks-icon-btn">{IC.more}</button></td>
                    </tr>
                  ))}
                </tbody>
              </table>

              {/* Footer */}
              <div style={{
                padding:'10px 16px',
                borderTop:'1px solid var(--ink-150)',
                background:'var(--ink-50)',
                display:'flex', alignItems:'center', gap:14, fontSize:12,
              }}>
                <span className="muted">Showing 1–8 of 18,470</span>
                <div className="grow"/>
                <div className="row gap-2">
                  <button className="btn ghost text-xs">←</button>
                  {[1,2,3,4,'…',2308].map((p,i)=>(
                    <button key={i} className="btn ghost text-xs" style={{
                      background: p === 1 ? 'var(--mod-db-tint)' : 'transparent',
                      color: p === 1 ? 'var(--mod-db)' : undefined,
                      fontWeight: p === 1 ? 600 : 500,
                      minWidth: 28, height: 24,
                    }}>{p}</button>
                  ))}
                  <button className="btn ghost text-xs">→</button>
                </div>
              </div>
            </div>
          )}

          {view === 'query' && (
            <div style={{flex:1, display:'flex', flexDirection:'column', background:'var(--white)', overflow:'hidden'}}>
              {/* AI prompt bar */}
              <div style={{padding:14, borderBottom:'1px solid var(--ink-150)', background:'linear-gradient(135deg, #F7F3FF, #FCFAFF)'}}>
                <div className="row gap-2" style={{marginBottom:6}}>
                  <div className="ai-avatar" style={{width:22, height:22, fontSize:10, borderRadius:5}}>K</div>
                  <span style={{fontSize:12.5, fontWeight:600}}>Ask in plain English — I'll generate the SQL</span>
                </div>
                <div style={{
                  background:'var(--white)', border:'1px solid #E4D6FA',
                  borderRadius:8, padding:'8px 12px', fontSize:13,
                  color:'var(--ink-800)',
                }}>
                  "Show me high-priority open grievances filed this month, grouped by department, with SLA breaches highlighted"
                </div>
              </div>

              {/* SQL editor */}
              <div style={{padding: 14, borderBottom:'1px solid var(--ink-150)'}}>
                <div className="row" style={{marginBottom:8}}>
                  <span className="text-xs muted b-500" style={{letterSpacing:'0.06em', textTransform:'uppercase'}}>Generated SQL</span>
                  <div className="grow"/>
                  <button className="btn ghost text-xs">{IC.copy}</button>
                  <button className="btn ghost text-xs">Explain</button>
                  <button className="btn primary text-xs">Run ▶</button>
                </div>
                <pre style={{
                  margin:0, padding:'12px 14px',
                  background:'#0F172A', color:'#E2E8F0',
                  borderRadius:8, fontFamily:'var(--f-mono)', fontSize:12.5,
                  lineHeight:1.6, overflow:'auto',
                }}>
{`SELECT `}<span style={{color:'#93C5FD'}}>d.name</span>{` AS department,
       COUNT(*) AS total_open,
       SUM(CASE WHEN g.sla_breached THEN 1 ELSE 0 END) AS breached,
       ROUND(AVG(EXTRACT(EPOCH FROM (NOW() - g.filed_at))/86400), 1) AS avg_days_open
`}<span style={{color:'#93C5FD'}}>FROM</span>{` grievances g
`}<span style={{color:'#93C5FD'}}>JOIN</span>{` departments d ON d.id = g.department_id
`}<span style={{color:'#93C5FD'}}>WHERE</span>{` g.status = 'Open'
  `}<span style={{color:'#93C5FD'}}>AND</span>{` g.priority = 'High'
  `}<span style={{color:'#93C5FD'}}>AND</span>{` g.filed_at >= date_trunc('month', CURRENT_DATE)
`}<span style={{color:'#93C5FD'}}>GROUP BY</span>{` d.name
`}<span style={{color:'#93C5FD'}}>ORDER BY</span>{` breached DESC, total_open DESC;`}
                </pre>
              </div>

              {/* Results */}
              <div style={{flex:1, overflow:'auto'}}>
                <div style={{padding:'8px 14px', fontSize:11.5, color:'var(--ok)', borderBottom:'1px solid var(--ink-150)', background:'var(--ok-tint)'}}>
                  ✓ Query completed in 84 ms · 6 rows
                </div>
                <table className="ks-table">
                  <thead><tr>
                    <th>Department</th>
                    <th>Total Open</th>
                    <th>Breached</th>
                    <th>Avg. days open</th>
                  </tr></thead>
                  <tbody>
                    {[
                      ['Public Distribution', 341, 47, 8.2],
                      ['Revenue',             289, 31, 6.7],
                      ['Housing',             211, 24, 9.1],
                      ['Social Welfare',      184, 12, 4.4],
                      ['UIDAI',               142,  9, 3.8],
                      ['Education',            89,  4, 5.1],
                    ].map((r, i) => (
                      <tr key={i}>
                        <td>{r[0]}</td>
                        <td className="mono">{r[1]}</td>
                        <td className="mono" style={{color: r[2] > 30 ? 'var(--err)' : r[2] > 15 ? 'var(--warn)' : 'var(--ink-800)', fontWeight: r[2] > 30 ? 600 : 400}}>{r[2]}</td>
                        <td className="mono">{r[3]}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {view === 'form' && (
            <div style={{flex:1, overflow:'auto', background:'var(--ink-100)', padding:24}}>
              <div style={{maxWidth: 640, margin:'0 auto', background:'var(--white)', border:'1px solid var(--ink-150)', borderRadius:12, padding:28, boxShadow:'var(--sh-1)'}}>
                <div className="row" style={{marginBottom: 4}}>
                  <span className="chip" style={{fontSize:11}}>Form Designer</span>
                  <div className="grow"/>
                  <button className="btn ghost text-xs">Preview</button>
                  <button className="btn primary text-xs">Publish</button>
                </div>
                <h2 style={{fontSize:22, fontWeight:700, margin:'8px 0 2px'}}>File a new grievance</h2>
                <p className="muted" style={{margin:0, fontSize:13}}>All fields marked <span style={{color:'var(--err)'}}>*</span> are required. Your data is protected under the DPDP Act, 2023.</p>

                <div className="col gap-4" style={{marginTop: 20}}>
                  {[
                    {l:'Full name (as per Aadhaar)', req:true, kind:'text', ph:'e.g. Bharti Devi'},
                    {l:'Aadhaar last 4 digits',      req:true, kind:'text', ph:'XXXX XXXX 1234'},
                    {l:'Mobile',                     req:true, kind:'text', ph:'+91'},
                    {l:'Category',                   req:true, kind:'select', opts:['Ration Card','Land Records','Pension','Aadhaar Correction','Other']},
                    {l:'Department',                 req:true, kind:'select', opts:['Public Distribution','Revenue','Social Welfare','UIDAI']},
                    {l:'Describe your grievance',    req:true, kind:'textarea'},
                    {l:'Upload supporting documents',req:false, kind:'file'},
                  ].map((f, i) => (
                    <div key={i}>
                      <label style={{fontSize:12.5, fontWeight:550, color:'var(--ink-700)', display:'block', marginBottom:4}}>
                        {f.l} {f.req && <span style={{color:'var(--err)'}}>*</span>}
                      </label>
                      {f.kind === 'textarea' ? (
                        <textarea rows="4" style={{
                          width:'100%', border:'1px solid var(--ink-200)', borderRadius:6,
                          padding:'8px 10px', fontSize:13, resize:'vertical', fontFamily:'inherit',
                        }}/>
                      ) : f.kind === 'select' ? (
                        <select style={{
                          width:'100%', border:'1px solid var(--ink-200)', borderRadius:6,
                          padding:'8px 10px', fontSize:13, background:'var(--white)',
                        }}>
                          <option>Select…</option>
                          {f.opts.map(o => <option key={o}>{o}</option>)}
                        </select>
                      ) : f.kind === 'file' ? (
                        <div style={{
                          border:'1.5px dashed var(--ink-300)', borderRadius:6,
                          padding:'20px', textAlign:'center', fontSize:12.5, color:'var(--ink-500)',
                          background:'var(--ink-50)',
                        }}>Drop files here or click to browse · PDF, JPG (max 10 MB)</div>
                      ) : (
                        <input placeholder={f.ph} style={{
                          width:'100%', border:'1px solid var(--ink-200)', borderRadius:6,
                          padding:'8px 10px', fontSize:13,
                        }}/>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {view === 'schema' && (
            <div style={{flex:1, overflow:'auto', background:'var(--canvas)', padding:24}}>
              <div style={{position:'relative', minWidth: 900, minHeight: 400}}>
                {[
                  {n:'grievances', x:60, y:20, fields:[['id','uuid','PK'],['citizen_id','uuid','FK'],['dept_id','uuid','FK'],['category','text'],['status','enum'],['priority','enum'],['filed_at','tstz'],['sla_breached','bool']]},
                  {n:'citizens',   x:400, y:20, fields:[['id','uuid','PK'],['aadhaar_hash','bytea'],['name','text'],['mobile','text'],['created_at','tstz']]},
                  {n:'departments',x:700, y:20, fields:[['id','uuid','PK'],['name','text'],['ministry','text'],['sla_days','int']]},
                  {n:'audit_trail',x:60, y:320, fields:[['id','bigint','PK'],['case_id','uuid','FK'],['event','text'],['actor','text'],['at','tstz']]},
                ].map(t => (
                  <div key={t.n} style={{
                    position:'absolute', left:t.x, top:t.y, width:260,
                    background:'var(--white)', border:'1px solid var(--ink-200)',
                    borderRadius:8, boxShadow:'var(--sh-1)',
                  }}>
                    <div style={{padding:'8px 12px', background:'var(--mod-db-tint)', borderBottom:'1px solid var(--ink-200)', borderRadius:'8px 8px 0 0'}}>
                      <div className="row gap-2">
                        {IC.db}
                        <span className="mono" style={{fontWeight:700, fontSize:12.5, color:'var(--mod-db)'}}>{t.n}</span>
                      </div>
                    </div>
                    {t.fields.map((f, i) => (
                      <div key={i} className="row" style={{
                        padding:'4px 12px', fontSize:11.5, fontFamily:'var(--f-mono)',
                        borderTop: i === 0 ? 'none' : '1px solid var(--ink-100)',
                      }}>
                        <span style={{flex:1, color: f[2] === 'PK' ? 'var(--mod-db)' : 'var(--ink-800)', fontWeight: f[2] === 'PK' ? 600 : 500}}>{f[0]}</span>
                        <span className="muted">{f[1]}</span>
                        {f[2] && <span className="chip" style={{marginLeft:6, fontSize:9.5, padding:'0 5px', background: f[2]==='PK' ? 'var(--mod-db-tint)':'var(--ink-100)', color: f[2]==='PK' ? 'var(--mod-db)':'var(--ink-600)'}}>{f[2]}</span>}
                      </div>
                    ))}
                  </div>
                ))}
                <svg style={{position:'absolute', inset:0, pointerEvents:'none'}} width="900" height="400">
                  <line x1="320" y1="45" x2="400" y2="45" stroke="var(--ink-400)" strokeWidth="1.5"/>
                  <line x1="320" y1="65" x2="700" y2="45" stroke="var(--ink-400)" strokeWidth="1.5"/>
                  <line x1="180" y1="200" x2="180" y2="320" stroke="var(--ink-400)" strokeWidth="1.5" strokeDasharray="4 3"/>
                </svg>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.ModuleDB = ModuleDB;
