const { useState, useEffect, useRef } = React;

const WORKER_URL = '';

function CFManager() {
  const [user, setUser] = useState(null);
  const [command, setCommand] = useState('');
  const [output, setOutput] = useState(['> NCS CloudFlare Manager v1.0\n> Type "help" for available commands\n']);
  const [loading, setLoading] = useState(false);
  const terminalRef = useRef(null);

  // Get user from Zero Trust header
  useEffect(() => {
    const getUserInfo = async () => {
      try {
        const res = await fetch(`${WORKER_URL}/api/user`);
        const data = await res.json();
        setUser(data.email);
      } catch (err) {
        addOutput('Error: Could not authenticate. Ensure Zero Trust policy is configured.');
      }
    };
    getUserInfo();
  }, []);

  // Auto-scroll terminal
  useEffect(() => {
    if (terminalRef.current) {
      terminalRef.current.scrollTop = terminalRef.current.scrollHeight;
    }
  }, [output]);

  const addOutput = (text) => {
    setOutput(prev => [...prev, text]);
  };

  const executeCommand = async (cmd) => {
    if (!cmd.trim()) return;

    addOutput(`> ${cmd}`);
    setCommand('');
    setLoading(true);

    try {
      const res = await fetch(`${WORKER_URL}/api/execute`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ command: cmd })
      });

      const data = await res.json();
      if (data.success) {
        addOutput(data.output);
      } else {
        addOutput(data.output || 'Error: Unknown error');
      }
    } catch (err) {
      addOutput(`Error: ${err.message}`);
    }

    setLoading(false);
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      executeCommand(command);
    }
  };

  return (
    <div style={styles.container}>
      <div style={styles.header}>
        <div style={styles.logoSection}>
          <div style={styles.logo}>NCS</div>
          <div>
            <h1 style={styles.title}>CloudFlare Manager</h1>
            <p style={styles.tagline}>Manage Workers & Pages</p>
          </div>
        </div>
        {user && <div style={styles.user}>Logged in: {user}</div>}
      </div>

      <div style={styles.terminalContainer}>
        <div ref={terminalRef} style={styles.terminal}>
          {output.map((line, idx) => (
            <div key={idx} style={styles.terminalLine}>
              {line}
            </div>
          ))}
        </div>

        <div style={styles.inputContainer}>
          <span style={styles.prompt}>❯</span>
          <input
            type="text"
            value={command}
            onChange={(e) => setCommand(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="Enter command..."
            disabled={loading}
            style={styles.input}
            autoFocus
          />
        </div>
      </div>

      <div style={styles.footer}>
        <p>NCS Your Trusted Technology Partner</p>
      </div>
    </div>
  );
}

const styles = {
  container: {
    display: 'flex',
    flexDirection: 'column',
    height: '100vh',
    backgroundColor: '#0a0e27',
    color: '#4CB81A',
    fontFamily: 'Verdana, monospace',
    overflow: 'hidden'
  },
  header: {
    backgroundColor: '#1a1f3a',
    padding: '20px',
    borderBottom: '2px solid #4CB81A',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  logoSection: {
    display: 'flex',
    alignItems: 'center',
    gap: '15px'
  },
  logo: {
    width: '50px',
    height: '50px',
    backgroundColor: '#4CB81A',
    color: '#0a0e27',
    borderRadius: '8px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontWeight: 'bold',
    fontSize: '24px'
  },
  title: {
    margin: '0',
    fontSize: '24px',
    color: '#4CB81A'
  },
  tagline: {
    margin: '5px 0 0 0',
    fontSize: '12px',
    color: '#888'
  },
  user: {
    fontSize: '14px',
    color: '#888',
    textAlign: 'right'
  },
  terminalContainer: {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    padding: '20px',
    gap: '10px',
    overflow: 'hidden'
  },
  terminal: {
    flex: 1,
    backgroundColor: '#0f1527',
    border: '1px solid #2a3f5f',
    borderRadius: '8px',
    padding: '15px',
    overflowY: 'auto',
    fontFamily: 'Courier New, monospace',
    fontSize: '14px',
    lineHeight: '1.6',
    color: '#4CB81A'
  },
  terminalLine: {
    whiteSpace: 'pre-wrap',
    wordBreak: 'break-word'
  },
  inputContainer: {
    display: 'flex',
    alignItems: 'center',
    gap: '10px',
    backgroundColor: '#0f1527',
    border: '1px solid #2a3f5f',
    borderRadius: '8px',
    padding: '10px 15px'
  },
  prompt: {
    color: '#4CB81A',
    fontSize: '16px'
  },
  input: {
    flex: 1,
    backgroundColor: 'transparent',
    border: 'none',
    color: '#4CB81A',
    fontFamily: 'Courier New, monospace',
    fontSize: '14px',
    outline: 'none'
  },
  footer: {
    backgroundColor: '#1a1f3a',
    borderTop: '2px solid #4CB81A',
    padding: '15px',
    textAlign: 'center',
    fontSize: '12px',
    color: '#888'
  }
};

ReactDOM.createRoot(document.getElementById('root')).render(<CFManager />);
